iOS10采用了新的通知框架,相比较原来的框架,功能丰富了不少,在使用前需引入框架
@import UserNotifications;
使用前需要用户授权
if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
//设置代理
center.delegate = self;
//获取用户的推送授权 iOS 10新方法
[center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
completionHandler:^(BOOL granted, NSError * _Nullable error) {
}];
//获取当前的通知设置,UNNotificationSettings 是只读对象,readOnly,只能通过以下方法获取
[center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
}];
}
委托方法,记得加入
<UNUserNotificationCenterDelegate>
#pragma mark -
#pragma mark - UNUserNotificationCenterDelegate
//在展示通知前进行处理,即有机会在展示通知前再修改通知内容。
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
//1. 处理通知
//2. 处理完成后条用 completionHandler ,用于指示在前台显示通知的形式
completionHandler(UNNotificationPresentationOptionAlert);
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler {
// 点击通知的处理
NSLog(@"didReceiveNotificationResponse");
}
如何发送通知:
UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
// > 需创建一个包含待通知内容的 UNMutableNotificationContent 对象,可变 UNNotificationContent 对象,不可变
// > 通知内容
UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];
// > 通知的title
content.title = [NSString localizedUserNotificationStringForKey:[NSString stringWithFormat:@"From: %@",_info[@"name"]] arguments:nil];
// > 通知的要通知内容
content.body = [NSString localizedUserNotificationStringForKey:[NSString stringWithFormat:@"%@",_info[@"title"]]
arguments:nil];
// > 通知的提示声音
content.sound = [UNNotificationSound defaultSound];
content.userInfo = @{@"content":_info};
// > 通知的延时执行
UNTimeIntervalNotificationTrigger* trigger = [UNTimeIntervalNotificationTrigger
triggerWithTimeInterval:5 repeats:NO];
UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:@"FiveSecond"
content:content trigger:trigger];
//添加推送通知,等待通知即可!
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
// > 可在此设置添加后的一些设置
// > 例如alertVC。。
}];
以上就是基本的使用流程了。