iOS有两套通知API, iOS10前使用UILocalNotification, 以后使用UNUserNotificationCenter.
UILocalNotification, iOS8以后应用需要registerUserNotificationSettings:
函数注册通知.
if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
UNUserNotificationCenter, iOS10使用requestAuthorizationWithOptions:
函数注册通知.
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
}];
接受UNUserNotificationCenterDelegate代理.
当iOS10以后, 当应用在前台, 通知默认是不显示的. 显示通知实现UNUserNotificationCenterDelegate
代理
userNotificationCenter
函数
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
completionHandler(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionSound);
}
User Notifications
iOS8 本地推送 UILocalNotification
iOS10 本地推送 UNUserNotificationCenter