Local Notification not triggering after changing device time in iOS - ios

I have local notification setup in one of my application which remind the user regarding medication on a regular basis and n times daily depends on user selection. If the user setup the reminder in the application and changes the date on device setting, reminder not triggering for the next scheduled time. But works fine for the other scheduled times. First notification scheduled is missing. Works fine for normal scenarios. Anyone faced similar issues? TIA. Code snippet as follows:
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center setNotificationCategories:[NSSet set]];
UNAuthorizationOptions options = UNAuthorizationOptionAlert + UNAuthorizationOptionSound + UNAuthorizationOptionBadge;
[center requestAuthorizationWithOptions:options
completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!granted) {
PRLog(#"Something went wrong");
}else{
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] registerForRemoteNotifications];
});
[LocalNotificationShared registerCategories];
}
}];
}
and triggering part like:
NSDateComponents *triggerDate = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitTimeZone fromDate:date]; UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:triggerDate repeats:NO];
NSString *s = [NSString stringWithFormat:#"%#",#([NSDate timeIntervalSinceReferenceDate])];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:s
content:content trigger:trigger];
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (error != nil) {
PRLog(#"Something went wrong: %#",error);
}
}];

From what I've observed, the time interval for a scheduled notification is independent of the device time. So if you schedule a notification for an hour away, and then set your device time to 59 minutes ahead, it won't matter - you will still have to wait the full hour for it to trigger.

Related

All delivered Scheduled Notifications are cleared from Notification Center when one is tapped

I scheduled multiple Local Notification for the user. All of them are also delivered on their specified time. However, when I try to open any one of them from Notification Center, all of them are getting cleared.
In a rightful scenario, I don't want all them to be cleared from notification centre, only those which are tapped to be opened.
Also, i tried commenting below code from AppDelegate.m, but the issue still persists. [[UIApplicationsharedApplication]setApplicationIconBadgeNumber:0];
Can anyone tell me what could be the issue here due to which my scheduled notifications are cleared from Notification Center even when I'm tapping to open only one of them?
Below is the code I'm using to schedule Local Notifications -
NSDateComponents *components = [SSUtility hoursMinuteAndSectionsForDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];
NSLog(#"Hour %ld Min %ld ", hour,minute);
UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:YES];
/* Set notification */
UNMutableNotificationContent *content = [UNMutableNotificationContent new];
content.body = body;
// content.categoryIdentifier=NSNotificationC;
content.sound = [UNNotificationSound defaultSound];
content.userInfo = userInfo;
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier
content:content
trigger:trigger];
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (error != nil) {
SSLOG(#"Something went wrong: %#",error);
}
}];
So i did't believe that this is a default behaviour so what i found:
if you use UNCalendarNotificationTrigger then all delivered reminders are deleted on tap
if you use UNTimeIntervalNotificationTrigger then delivered reminders remain on the notification center
so try to use the UNTimeIntervalNotificationTrigger instead of UNCalendarNotificationTrigger
NSTimeInterval timeInterval = [fireDate timeIntervalSinceDate:[NSDate date]];
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:timeInterval repeats:NO];
In my case, Add some text to content.body solve the problem:
content.body = 'Any text'

WatchOS App 4.0: How to schedule a local notification

My application in background or inactive mode then local notification not work. I have never receive local notification on watch.
Update: less then 3 minutes schedule a local notification it's work fine but more then 3 minutes it's not work. so how to resolve this issues?
As per my understanding My code is as follows.
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
// Objective-C
UNMutableNotificationContent *content = [UNMutableNotificationContent new];
content.title = [NSString localizedUserNotificationStringForKey:#"Remider!" arguments:nil];
content.body = [NSString localizedUserNotificationStringForKey:#"Your watch is out of range" arguments:nil];
content.sound = [UNNotificationSound defaultSound];
// Time
// 15 min
double timer = 15*60;
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:time
repeats:NO];
// Actions
UNNotificationAction *snoozeAction = [UNNotificationAction actionWithIdentifier:#"Track"
title:#"Track" options:UNNotificationActionOptionForeground];
// Objective-C
UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:#"UYLReminderCategory"
actions:#[snoozeAction] intentIdentifiers:#[]
options:UNNotificationCategoryOptionCustomDismissAction];
NSSet *categories = [NSSet setWithObject:category];
// Objective-C
[center setNotificationCategories:categories];
// Objective-C
content.categoryIdentifier = #"UYLReminderCategory";
NSString *identifier = [self stringUUID];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier
content:content trigger:trigger];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(#"Something went wrong: %#",error);
}
}];
Appreciate if any suggestion or idea.
Make sure your iphone is locked. When it comes to notification, its about preference where to deliver that notification.
Run your watch app on simulator, from iPhone simulator schedule the notification and lock the iPhone simulator screen, keep the watch simulator active, in that case when notification is triggered , it will be delivered on your watch simulator. Same will be the case when you will test on actual devices.
Source Link
And when both iphone and watch is locked, preference is iphone.
UPDATE
Notification on Apple Watch

how cancel local single notification in objective c

Can u help me how to cancel local notification in iOS 10
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center removeAllPendingNotificationRequests];
[center removePendingNotificationRequestsWithIdentifiers:#[ CYLInviteCategoryIdentifier ]];
removePendingNotificationRequestsWithIdentifiers i cant understand
While creating a Local notification, you can pass an identifier to each notification. Use the same identifier to remove the local notification.
Code to create local notification:-
NSString *identifier = #"Unique Identifier";
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger]
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(#"Something went wrong: %#",error);
}
}];
Code to Cancel Notification:-
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
NSArray *array = [NSArray arrayWithObjects:#"Identifier1",#"Identifier2", nil];
[center removePendingNotificationRequestsWithIdentifiers:array];
Try this
[[UNUserNotificationCenter currentNotificationCenter]getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) {
NSLog(#"count%lu",(unsigned long)requests.count);
if (requests.count>0) {
UNNotificationRequest *pendingRequest = [requests objectAtIndex:0];
if ([pendingRequest.identifier isEqualToString:#"identifier"]) {
[[UNUserNotificationCenter currentNotificationCenter]removePendingNotificationRequestsWithIdentifiers:#[pendingRequest.identifier]];
}
}
}];
I don't use any of the above solutions. I don't cancel any single notifications. Rather, whenever the user runs the app I cancel ALL the local notifications and run the code that recreates them all with the new parameters, which will cancel any local notifications that need cancelling. Less code surface, less to test, creating notifications is generally an inexpensive operation. Many, many apps use this solution, consider whether you could use this yourself.
You can use below code to remove single local notification.
UIApplication *app = [UIApplication sharedApplication];
NSArray *allLocalNoti = [app scheduledLocalNotifications];
for (int i=0; i<[allLocalNoti count]; i++)
{
UILocalNotification* currentLocalNotification = [allLocalNoti objectAtIndex:i];
NSDictionary *userInfoCurrent = currentLocalNotification.userInfo;
NSString *uid=[NSString stringWithFormat:#"%#",[userInfoCurrent valueForKey:#"uid"]];
if ([uid isEqualToString:uidtodelete])
{
[app cancelLocalNotification:currentLocalNotification];
break;
}
}
Happy Coding...

Local notification UNTimeIntervalNotificationTrigger triggerWithTimeInterval fires for 20 minutes then stops

I am using local notifications in my app to alert urgent messages to the user. What happens is the user receives a push notification, then a local notification is created and fired 60 seconds later with a time interval of 60 seconds. This works great and the urgent notification fires every 60 seconds as expected.
The problem is after about 20 minutes the local notification stops firing. This does not occur all the time and sometimes the notification can fire for hours with no problem. However, this problem seems to occur more often than not.
On iOS 9 we did not experience this problem at all and the notification would fire repeatedly overnight even, so I am thinking this might be something related to iOS 10?
I've also got a hunch that perhaps this has to do with memory pressure from the OS? If I attach to xCode and debug then the problem does not occur at all and will fire into infinity.
The code I use to create the notification is as follows:
[[UNUserNotificationCenter currentNotificationCenter] getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) {
dispatch_async(dispatch_get_main_queue(), ^{
//If notification already exists then kill it with fire
[self removeAllLocalNotifications];
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
content.title = #"Urgent";
content.sound = [UNNotificationSound soundNamed:#"dingdingding.wav"];
content.categoryIdentifier = #"urgentCategoryId";
content.body = #"You have an urgent message.";
// Deliver the notification in scheduled amount of seconds.
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:60 repeats:YES];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:#"urgentMessageId" content:content trigger:trigger];
// Schedule the notification.
[[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (error) {
NSLog(#"Notification creation Error");
}
if (completionHandler) {
completionHandler(UIBackgroundFetchResultNewData);
}
});
}];
});
}];
Any help would be much appreciated as this is a very frustrating issue.

UNNotification: Custom Sound for LocalNotification is not playing in iOS10

I'm firing a local notification. Since UILocalNotification class is deprecated in iOS 10, I have used UserNotifications.framework.
When I try to set the custom sound for the notification, the default sound is playing all time.
Here is my code:
- (IBAction)fireLocalNotification:(id)sender {
UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];
content.title = [NSString localizedUserNotificationStringForKey:#"Hello!" arguments:nil];
content.body = [NSString localizedUserNotificationStringForKey:#"Hello_message_body"
arguments:nil];
content.sound = [UNNotificationSound soundNamed:#"sound.mp3"];
// Deliver the notification in five seconds.
UNTimeIntervalNotificationTrigger* trigger = [UNTimeIntervalNotificationTrigger
triggerWithTimeInterval:5 repeats:NO];
UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:#"FiveSecond"
content:content trigger:trigger];
// Schedule the notification.
UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
[center addNotificationRequest:request withCompletionHandler:^(NSError *error){
if(!error){
NSLog(#"Completion handler for notification");
}
}];
}
My sound is fine; sound.mp3 is present in project bundle itself.
More info:
https://developer.apple.com/reference/usernotifications/unusernotificationcenter?language=objc
Try deleting the app from the device, clean and run the app again on device.
Sometimes, resources are not properly updated; I think that is the problem in your case.
Long audio-files are not supported.
Is your file longer then 30 seconds? If yes, it will not work. Only files shorter then 30 seconds are available. If the file is longer then 30 seconds then it will be replaced with default sound.
UNNotificationSound documentation

Resources