- 引入頭文件
#import <UserNotifications/UserNotifications.h>
- 注冊(cè)通知
/*
注冊(cè)通知(推送)
申請(qǐng)App需要接受來(lái)自服務(wù)商提供推送消息
*/
if (@available(iOS 10.0, *)) {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!granted) {
[self showNoticeAlert];
}
}];
// 注冊(cè)遠(yuǎn)程通知
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
- 檢查通知權(quán)限
- (void)checkNotificationAuth:(void(^)(BOOL granted))block
{
if (@available(iOS 10.0, *)) {
[[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
if (settings.authorizationStatus == UNAuthorizationStatusAuthorized) {
block(YES);
}else {
block(NO);
}
}];
}else {
if ([[UIApplication sharedApplication] currentUserNotificationSettings].types == UIUserNotificationTypeNone) {
block(NO);
}else {
block(YES);
}
}
}
- 發(fā)送本地通知
if (@available(iOS 10.0, *)) {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
content.title = @"title";
content.body = @"body";
content.badge = 0;
content.userInfo = @{};
NSTimeInterval timeInterval = [[NSDate dateWithTimeIntervalSinceNow:1] timeIntervalSinceNow];
// repeats,是否重復(fù),如果重復(fù)的話時(shí)間必須大于60s昙读,要不會(huì)報(bào)錯(cuò)
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:timeInterval repeats:NO];
UNNotificationRequest *reqeust = [UNNotificationRequest requestWithIdentifier:@"noticeIdentifier" content:content trigger:trigger];
[center addNotificationRequest:reqeust withCompletionHandler:^(NSError * _Nullable error) {
if (error) {
DLog(@"error");
}
}];
}
5.發(fā)送本地通知一定要實(shí)現(xiàn)以下代理方法
//App在前臺(tái)時(shí)候回調(diào):用戶正在使用狀態(tài)
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionAlert);
}
- 通知代理方法
// 推送消息回調(diào)
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler
{
if ([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
// 遠(yuǎn)程推送消息處理
} else {
// 本地消息處理
}
completionHandler();
}