標籤:
最近在做一個電商的APP,話說今年電商很火啊。 用到了本地通知,特此整理一下
添加一個本地通知到系統中,代碼如下:
// 初始化本地通知對象UILocalNotification *notification = [[UILocalNotification alloc] init];if (notification) { // 設定通知的提醒時間 NSDate *currentDate = [NSDate date]; notification.timeZone = [NSTimeZone defaultTimeZone]; // 使用本地時區 notification.fireDate = [currentDate dateByAddingTimeInterval:5.0]; // 設定重複間隔 notification.repeatInterval = kCFCalendarUnitDay; // 設定提醒的文字內容 notification.alertBody = @"Wake up, man"; notification.alertAction = NSLocalizedString(@"該吃藥了", nil); // 通知提示音 使用預設的 notification.soundName= UILocalNotificationDefaultSoundName; // 設定應用程式右上方的提醒個數 notification.applicationIconBadgeNumber++; // 設定通知的userInfo,用來標識該通知 NSMutableDictionary *aUserInfo = [[NSMutableDictionary alloc] init]; aUserInfo[kLocalNotificationID] = @"LocalNotificationID"; notification.userInfo = aUserInfo; // 將通知添加到系統中 [[UIApplication sharedApplication] scheduleLocalNotification:notification];}
在APPDelegate.m中 加入接受本地通知的代碼 :
在收到通知後,調用程式委託中的下列方法處理://當然方法中可以是跳轉到指定頁面等方式,這裡是一個彈出框
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{ NSLog(@"Application did receive local notifications"); UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hello" message:@"welcome" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; [alert show];
}
最近看大牛的部落格,說是本地通知在APP卸載後,還會存在系統中,
可以看一下,列印一下所有的,驗證一下
12NSArray *localNotifications = [[UIApplication sharedApplication] scheduledLocalNotifications];NSLog(@"%@", localNotifications);
那麼怎麼刪除本地通知呢,大牛也給出了方法
取消方法分為兩種。
第一種比較暴力,直接取消所有的本地通知:
[[UIApplication sharedApplication] cancelAllLocalNotifications];
第二種方法是針對某個特定通知的:
- (void)cancelLocalNotification:(UILocalNotification *)notification NS_AVAILABLE_IOS(4_0);
這時就需要通知有一個標識,這樣我們才能定位是哪一個通知。可以在notification的userInfo(一個字典)中指定。
例如:
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{ NSLog(@"Application did receive local notifications"); // 取消某個特定的本地通知 for (UILocalNotification *noti in [[UIApplication sharedApplication] scheduledLocalNotifications]) { NSString *notiID = noti.userInfo[kLocalNotificationID]; NSString *receiveNotiID = notification.userInfo[kLocalNotificationID]; if ([notiID isEqualToString:receiveNotiID]) { [[UIApplication sharedApplication] cancelLocalNotification:notification]; return; } } UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hello" message:@"welcome" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; [alert show];}
iOS本地通知:UILocalNotification