UNUserNotificationCenter是iOS10 推出的新的通知中心 ,最近的项目涉及的比较深,我就总结了一下:
下面我们开始一步一步的来添加本地推送,
1、首先在开始注册通知:
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
//监听回调事件
center.delegate = self;
//iOS 10 使用以下方法注册,才能得到授权
[center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound +UNAuthorizationOptionBadge)
completionHandler:^(BOOL granted, NSError * _Nullable error) {
// Enable or disable features based on authorization.
}];
//获取当前的通知设置,UNNotificationSettings 是只读对象,不能直接修改,只能通过以下方法获取
[center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
}];
我们要首先注册通知中心的代理事件,注册通知,提醒用户获取通知权限:
- (void)requestAuthorizationWithOptions:(UNAuthorizationOptions)options completionHandler:(void (^)(BOOL granted, NSError *__nullable error))completionHandler;
(1)其中 UNAuthorizationOptions 是授权通知提醒的方式
UNAuthorizationOptionBa dge;
UNAuthorizationOptionSound;
UNAuthorizationOptionAlert;
UNAuthorizationOptionCarPlay;
这个根据需要填写。
(2)block中的 BOOL granted 与 NSError *__nullable error :
error 注册失败时错误抛出;
granted 为YES时得到用户授权,为NO�时授权失败 (用户不允许);
2、创建一个新的通知内容 UNMutableNotificationContent ,我们先了解一下这个类:
// 为通知中附加音频,图片,视频
@property (NS_NONATOMIC_IOSONLY, copy) NSArray <UNNotificationAttachment *> *attachments
//控制应用的badge的数量
@property (NS_NONATOMIC_IOSONLY, copy, nullable) NSNumber *badge;
//通知的消息体
@property (NS_NONATOMIC_IOSONLY, copy) NSString</