- 注册本地通知
iOS SDK 8 中的本地通知与之前的本地推送不同之处在于:iOS SDK 8中的本地通知也需要注册,而之前本地推送是不需要注册的。
if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]) { //设置通知的类型: alert、icon's badge、sound UIUserNotificationSettings *userNotificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert categories:nil]; //注册本地通知,会向用户索取授权 [[UIApplication sharedApplication] registerUserNotificationSettings:userNotificationSettings]; }
调用注册本地通知的方法,无论用户是否授权,均会调用以下代理方法。
如果用户未给予授权,notificationSettings.types = UIUserNotificationTypeNone。
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings { if (notificationSettings.types == UIUserNotificationTypeNone) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"您未授权本app通知权限" message:@"建议在xxx打开通知权限......" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil]; [alert show]; } }
此外可以调用以下方法判断用户是否授权了本地通知:
if ([UIApplication instancesRespondToSelector:@selector(currentUserNotificationSettings)]) { NSLog(@"settings:%@",[[UIApplication sharedApplication] currentUserNotificationSettings]); }
- 添加本地通知
添加一个本地推送:
UILocalNotification *newNotification = [[UILocalNotification alloc] init]; if (newNotification) { newNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5]; newNotification.alertBody = @"小懒猪,起床啦!"; newNotification.soundName = [NSString stringWithFormat:@"%@.caf", @"tips"]; newNotification.alertAction = @"起床闹钟"; newNotification.repeatInterval = NSWeekCalendarUnit; newNotification.userInfo = [NSDictionary dictionaryWithObject:@"起床闹钟" forKey:kString_notificationName]; [[UIApplication sharedApplication] scheduleLocalNotification:newNotification]; }
如果用户点击了本地通知的alert进入应用,或者应用运行在前台时本地通知触发(此时无论用户是否授权),均会调用以下代理方法。
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { NSString *notificationName = notification.userInfo[kString_notificationName]; NSString *title = nil; if ([notificationName isEqualToString:@"起床闹钟"]) { title = @"现在起床了"; } else if ([notificationName isEqualToString:@"吃饭闹钟"]) { title = @"现在吃饭了"; } UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil]; [alert show]; }
同样也可以查看已经添加的本地通知:
[[UIApplication sharedApplication] scheduledLocalNotifications];