眾所周知,iOS中的通知推送分為:本地和遠程兩種。本地推送主要用于日歷鬧鐘等提醒類應用中,APNS遠程推送以后專門寫一篇介紹,本文暫時按下不表。今天的主角是:UILocalNotification
啟動通知
創建一個本地通知:
//本地通知
UILocalNotification *localNoti = [[UILocalNotification alloc] init];
//時區
localNoti.timeZone = [NSTimeZone defaultTimeZone];
//觸發時間
localNoti.fireDate = [NSDate dateWithTimeIntervalSinceNow:10.0];
//重復間隔
localNoti.repeatInterval = kCFCalendarUnitSecond;
//通知內容
localNoti.alertBody = @"歡迎來到英雄聯盟";
//通知聲音
localNoti.soundName = UILocalNotificationDefaultSoundName;
//通知徽標
[UIApplication sharedApplication].applicationIconBadgeNumber += 1;
//通知參數
localNoti.userInfo = [NSDictionary dictionaryWithObject:@"傳遞信息內容" forKey:@"通知的Key"];
//發送通知:
[[UIApplication sharedApplication] scheduleLocalNotification:localNoti];
想要通知有效,需要在 application: didFinishLaunchingWithOptions:里注冊通知:
//注冊通知:
if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
效果圖如下:
IMG_0127.jpg
IMG_0128.jpg
IMG_0129.jpg
收到通知后的處理可以寫在方法 *application:(UIApplication )application didReceiveLocalNotification: 里面:
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"本地通知" message:[notification.userInfo allValues].firstObject preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cacel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"取消");
}];
UIAlertAction *action = [UIAlertAction actionWithTitle:@"確認" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"確認");
}];
[alert addAction:cacel];
[alert addAction:action];
[self.window.rootViewController presentViewController:alert animated:YES completion:nil];
取消通知
取消一個本地通知:
// 獲取所有本地通知數組
NSArray *localNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;
for (UILocalNotification *notification in localNotifications) {
NSDictionary *userInfo = notification.userInfo;
if (userInfo) {
// 根據設置通知參數時指定的key來獲取通知參數
NSString *info = userInfo[key];
// 如果找到需要取消的通知,則取消
if (info != nil) {
[[UIApplication sharedApplication] cancelLocalNotification:notification];
//圖標的數字清零
([UIApplication sharedApplication].applicationIconBadgeNumber >= 1) ?([UIApplication sharedApplication].applicationIconBadgeNumber -= 1):0 ;
break;
}
}
}