iOS Objective-C中newarr数组多时间匹配触发通知异常求助
Hey there! It sounds like you've got the basic notification trigger logic working, but only one notification fires even when multiple times in your newarr array match the current time. Let's break down the common issues and how to fix them.
1. Check Your Loop Logic (Most Likely Culprit)
If you're only checking the first element in newarr or breaking the loop after the first match, that's why only one notification fires. Make sure you iterate through the entire array without stopping early.
Example Correct Loop:
// Assume newarr stores time strings like @"10:00", @"15:30" NSArray *newarr = @[@"10:00", @"15:30", @"19:00"]; NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init]; [timeFormatter setDateFormat:@"HH:mm"]; NSString *currentTime = [timeFormatter stringFromDate:[NSDate date]]; // Loop through ALL elements in newarr for (NSString *targetTime in newarr) { if ([currentTime isEqualToString:targetTime]) { // Trigger notification for this matching time [self sendNotificationForTime:targetTime]; // DO NOT add a 'break;' here—this would stop after the first match! } }
2. Use Unique Notification Identifiers
iOS's UNUserNotificationCenter (the modern way to handle notifications) will overwrite existing notifications if they share the same identifier. You need to assign a unique ID to each notification so they all show up.
Example Notification Method with Unique ID:
- (void)sendNotificationForTime:(NSString *)targetTime { UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init]; content.title = @"Time Alert!"; content.body = [NSString stringWithFormat:@"It's now %@!", targetTime]; content.sound = [UNNotificationSound defaultSound]; // Create a unique identifier using the time (replace colon to make it valid) NSString *uniqueID = [NSString stringWithFormat:@"time_notif_%@", [targetTime stringByReplacingOccurrencesOfString:@":" withString:@""]]; // Trigger immediately since we already matched the time UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0 repeats:NO]; UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:uniqueID content:content trigger:trigger]; [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { if (error) { NSLog(@"Failed to schedule notification: %@", error.localizedDescription); } }]; }
3. Ensure You're Checking Time Continuously
If you only check the time once (e.g., on app launch), you'll miss future matches. Set up a way to re-check the time periodically or listen for system time changes:
Option A: Use a Timer (Check Every Minute)
// In your view controller's init or viewDidLoad NSTimer *timeCheckTimer = [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(checkForMatchingTimes) userInfo:nil repeats:YES]; [[NSRunLoop mainRunLoop] addTimer:timeCheckTimer forMode:NSRunLoopCommonModes]; // The selector method (same loop logic as before) - (void)checkForMatchingTimes { NSArray *newarr = @[@"10:00", @"15:30", @"19:00"]; NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init]; [timeFormatter setDateFormat:@"HH:mm"]; NSString *currentTime = [timeFormatter stringFromDate:[NSDate date]]; for (NSString *targetTime in newarr) { if ([currentTime isEqualToString:targetTime]) { [self sendNotificationForTime:targetTime]; } } }
Option B: Listen for System Time Changes
Apple provides a notification when the system time changes (e.g., user adjusts time, daylight savings):
// Register observer in init/viewDidLoad [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkForMatchingTimes) name:UIApplicationSignificantTimeChangeNotification object:nil];
Quick Troubleshooting Tips
- Verify that
newarractually contains multiple time strings that match the current time when you test. - Check if notifications are enabled for your app in Settings > Notifications.
- Test with different times to rule out edge cases (e.g., leading zeros like @"09:00" vs @"9:00").
内容的提问来源于stack exchange,提问作者iOS Developer

