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...
Related
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.
I have a code that allows the device to run an update. It works perfectly when the ipad is not under guided access for information under iOS11 (and it worked under iOS10 & guided accesss):
- (void)viewDidLoad
{
...
UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];
content.title = [NSString localizedUserNotificationStringForKey:#"Update!" arguments:nil];
content.body = [NSString localizedUserNotificationStringForKey:#"Update!"
arguments:nil];
// Configure the trigger for a 7am update.
NSDateComponents* date = [[NSDateComponents alloc] init];
date.hour = 18;
date.minute = 31;
UNCalendarNotificationTrigger* trigger = [UNCalendarNotificationTrigger
triggerWithDateMatchingComponents:date repeats:NO];
// Create the request object.
UNNotificationRequest* request = [UNNotificationRequest
requestWithIdentifier:#"update" content:content trigger:trigger];
UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(#"%#", error.localizedDescription);
}
}];
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
// Update the app interface directly.
NSLog(#"");
// Play a sound.
completionHandler(UNNotificationPresentationOptionSound);
}
I found that Ticket, but no exhaustive explanations to accomplish it:
Is it possible under iOS11 to launch notification on guided access?
Thanks in advance.
It appears this was nothing more than an iOS bug which has been fixed in iOS 11.2.5 beta 4. Please see my own question here for more information.
If you can wait until iOS 11.2.5 is released (which will hopefully be soon according to Apple) the issue should just resolve itself. Otherwise you'll need to investigate something like a sockets system instead.
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
I'm trying to add an action to the iOS remote notification.
This is the command I'm sending to houston (https://github.com/nomad/houston)
apn push "APNS_TOKEN_HERE" -c /Users/johannwerner/Desktop/apple_push_notification.pem -P '{"aps":{"alert":{"action-loc-key":"OK","title":"hello","body":"Hello"},"category":"ACTIONABLE"}}'
When the app launches from the push notification and I log launchOptions from the didFinishWithOptions method I get the following
{
UIApplicationLaunchOptionsRemoteNotificationKey = {
aps = {
alert = {
"action-loc-key" = OK;
body = Hello;
title = hello;
};
category = ACTIONABLE;
};
};
}
When I'm registering the notification in the code I'm using the following.
if (NSClassFromString(#"UNUserNotificationCenter")) {
UNNotificationAction* snoozeAction = [UNNotificationAction
actionWithIdentifier:#"SNOOZE_ACTION"
title:#"Snooze"
options:UNNotificationActionOptionNone];
UNNotificationCategory* generalCategory = [UNNotificationCategory
categoryWithIdentifier:#"GENERAL"
actions:#[snoozeAction]
intentIdentifiers:#[#"ACTIONABLE"]
options:UNNotificationCategoryOptionCustomDismissAction];
UNAuthorizationOptions options = (UNAuthorizationOptionBadge | UNAuthorizationOptionSound |UNAuthorizationOptionAlert);
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center setNotificationCategories:[NSSet setWithObjects:generalCategory, nil]];
center.delegate = self;
[center requestAuthorizationWithOptions:options completionHandler:^(BOOL granted, NSError * _Nullable error)
{
if( !error ){
[Localytics didRequestUserNotificationAuthorizationWithOptions:options
granted:granted];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
[[NSNotificationCenter defaultCenter] postNotificationName:PUSH_DELEGATE_AFTER_REGISTERED object: nil];
}];
}
I'm getting a push that has my title and body text of "hello" but there is no button or action on the push notification.
I'm been through this guide https://nrj.io/simple-interactive-notifications-in-ios-8/
as well as apples documentation
https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html#//apple_ref/doc/uid/TP40008194-CH10-SW1 for the payload
and https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/SupportingNotificationsinYourApp.html for adding actions to the notification.
Finally found it. In my payload I was sending category as string "actionable". It should be "GENERAL"
I am using UNUsernotification for iOS 10 and Xcode 8 Beta 2
I wrote below code for Local Notification in iOS device:
-(void) localNotificationForiOS10:(NSDate *) _reminderDate{
NSLog(#"_reminderDate %#",_reminderDate);
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
[calendar setTimeZone:[NSTimeZone localTimeZone]];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitTimeZone fromDate:_reminderDate];
NSLog(#"NSDateComponents %#",components);
UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
objNotificationContent.title = [NSString localizedUserNotificationStringForKey:#"Event Name!" arguments:nil];
objNotificationContent.body = [NSString localizedUserNotificationStringForKey:#"You have event reminder"
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:#"firedate"
content:objNotificationContent trigger:trigger];
/// 3. schedule localNotification
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (!error) {
NSLog(#"Local Notification succeeded");
}
else {
NSLog(#"Local Notification failed");
}
}];
}
I want to set three different or multiple future dates and want reminder of event on defined dates.
When I used the above code for 3 different time on same date
e.g. (2016-12-29 18:05 ,2016-12-29 18:10, 2016-12-29 18:15) than only last one gave notification.
I register Location notification in AppDelegate file.
application.applicationIconBadgeNumber = 0;
if ([[[UIDevice currentDevice] systemVersion] floatValue] > 10.0f) {
#if XCODE_VERSION_GREATER_THAN_OR_EQUAL_TO_8
/// schedule localNotification, the delegate must be set before the application returns from applicationDidFinishLaunching:.
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
#endif
} else {
UILocalNotification *localNotifacation = [self getLocalNotificationFromLaunchOptions:launchOptions];
if (localNotifacation) {
NSString *title = localNotifacation.alertBody;
NSLog(#"Add Title %#",title);
}
}
I tried my self and I tried it.
I am able to cancel the Local Notification in iOS 10.
here is posted code.
how to cancel a local notification in iphone