I wish to display a custom reminder or a pop up message either at the foreground or at the background of the app when it is time. I have tried this link but doesn't seems to work.
Nothing happened when I launch my app. It will say Local Notification succeeded but I don't see any pop up custom message box. Please help.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//===Every 20 secs I will call setSchedule method
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:20 target:self selector:@selector(setSchedule) userInfo:nil repeats:YES];
return YES;
}
-(void)setSchedule{
NSDate *now = [NSDate date];
NSLog(@"NSDate:%@",now);
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setTimeZone:[NSTimeZone localTimeZone]];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit|NSTimeZoneCalendarUnit fromDate:now];
UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
objNotificationContent.title = [NSString localizedUserNotificationStringForKey:@"Notification!" arguments:nil];
objNotificationContent.body = [NSString localizedUserNotificationStringForKey:@"This is local notification message!" arguments:nil];
objNotificationContent.sound = [UNNotificationSound defaultSound];
/// 4. update application icon badge number
objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);
UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:NO];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"ten" content:objNotificationContent trigger:trigger];
/// 3. schedule localNotification
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (!error) {
NSLog(@"Local Notification succeeded");
}
else {
NSLog(@"Local Notification failed");
}
}];
}
First thing is that UNUserNotification
not fire in foreground.
Second thing if you want to fire notification every 20 seconds or whatever time intervel then don't use UNCalendarNotificationTrigger
.
Check below trigger method and set in your code.
let trigger2 = UNTimeIntervalNotificationTrigger(timeInterval: YourInterval, repeats: true)