0%

iOS10添加本地通知

UILocalNotification 已经在 iOS10 中被废弃了。需要使用 UserNotifications.Framework 来推送通知。

获取权限

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
// 使用 UNUserNotificationCenter 来管理消息
UNUserNotificationCenter *unCenter = [UNUserNotificationCenter currentNotificationCenter];
// 注册回调代理
unCenter.delegate = self;
// 获取授权,第一次调用会弹出授权对话框
[unCenter requestAuthorizationWithOptions:UNAuthorizationOptionSound|UNAuthorizationOptionAlert|UNAuthorizationOptionBadge completionHandler:^(BOOL granted, NSError * _Nullable error) {
// granted 是否获取用户授权
}];
}

#pragma mark - UNUserNotificationCenterDelegate
// 收到通知时的回调
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
// 处理完通知后调用,通知系统已处理完毕
completionHandler();
}

注册本地通知

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// 注册通知
+ (void)registerLocalNotification {
UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];

// 通知内容,Mutable表示内容可变化
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
content.title = @"通知标题";
content.body = @"通知内容";
content.sound = UNNotificationSound.defaultSound; // 通知声音
// 自定义通知提示音
content.sound = [UNNotificationSound soundNamed:@"sound.wav"];
content.badge = @1; // 角标数字

// 触发器,10s 后推送本地通知
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10 repeats:NO];

// 注册本地通知
NSString *identifier = @"notification_id"; // 通知的id
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
NSLog(@"registerLocalPush error: %@", error);
}];
}

// 根据 identifier 取消指定的通知
+ (void)removeLocalNotification:(NSString*)identifier {
UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
[center removePendingNotificationRequestsWithIdentifiers:@[identifier]];
}

// 取消所有的通知
+ (void)removeAllLocalNotifications {
UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
[center removeAllDeliveredNotifications];
[center removeAllPendingNotificationRequests];
}

参考链接