第一步:导入头文件
#import <UserNotifications/UserNotifications.h>
#import <notify.h>
同时要遵循<UNUserNotificationCenterDelegate>
第二步: 获取通知权限
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self; // 必须写代理,不然无法监听通知的接收与点击
[center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted) {
// 点击允许 注册成功
[center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
}];
} else {
// 点击不允许 注册失败
}
}];
第三步:触发通知
// 新建通知内容对象(可以有内容、声音、图像等)
UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];
content.title = @"当前位置更新";
content.body = self.currentAddress;
content.sound = [UNNotificationSound defaultSound]; // 默认通知声音
// 通知触发机制。(重复提醒,时间间隔要大于60s
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:3.0 repeats:NO];
// 创建UNNotificationRequest通知请求对象
UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:requestIdentiferForLocation content:content trigger:trigger];
// 将通知加到通知中心
[[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:nil];
// 修改角标
[UIApplication sharedApplication].applicationIconBadgeNumber = 1;
网友评论