这篇文章开始,我会跟大家好好讲讲,苹果新发布的iOS10的所有通知类。
一、创建本地通知事例详解:
注意啊,小伙伴们,本地通知也必须在appdelegate中注册中心,通知的开关打不打开无所谓的,毕竟是本地通知,但是通知的接收的代理,以及通知点击的代理,苹果给合二为一了。所以大家还是需要在appdelegate中写上这2个方法,还有不要忘记在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions注册通知中心。如果使用极光推送的小伙伴,写看一下我的基础篇,辛苦大家啦
创建一个UNNotificationRequest类的实例,一定要为它设置identifier, 在后面的查找,更新, 删除通知,这个标识是可以用来区分这个通知与其他通知
把request加到UNUserNotificationCenter, 并设置触发器,等待触发
如果另一个request具有和之前request相同的标识,不同的内容, 可以达到更新通知的目的
创建一个本地通知我们应该先创建一个UNNotificationRequest类,并且将这个类添加到UNUserNotificationCenter才可以。代码如下:
// 1.创建一个UNNotificationRequest
NSString *requestIdentifer = @"TestRequest";
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requestIdentifer content:content trigger:trigger];
// 2.将UNNotificationRequest类,添加进当前通知中心中
[[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
}];
在创建UNNotificationRequest类时,官方的解释是说,一个通知请求可以在预定通过时间和位置,来通知用户。触发的方式见UNNotificationTrigger的相关说明。调用该方法,在通知触发的时候。会取代具有相同标识符的通知请求,此外,消息个数受系统限制。
上面的翻译,看上去可能有些拗口,简单来说,就是我们需要为UNNotificationRequest设置一个标识符,通过标识符,我们可以对该通知进行添加,删除,更新等操作。
以下是完整的创建通知的代码:
// 1.创建通知内容
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
content.title = @"徐不同测试通知";
content.subtitle = @"测试通知";
content.body = @"来自徐不同的简书";
content.badge = @1;
NSError *error = nil;
NSString *path = [[NSBundle mainBundle] pathForResource:@"icon_certification_status1@2x" ofType:@"png"];
// 2.设置通知附件内容
UNNotificationAttachment *att = [UNNotificationAttachment attachmentWithIdentifier:@"att1" URL:[NSURL fileURLWithPath:path] options:nil error:&error];
if (error) {
NSLog(@"attachment error %@", error);
}
content.attachments = @[att];
content.launchImageName = @"icon_certification_status1@2x";
// 2.设置声音
UNNotificationSound *sound = [UNNotificationSound defaultSound];
content.sound = sound;
// 3.触发模式
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO];
// 4.设置UNNotificationRequest
NSString *requestIdentifer = @"TestRequest";
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requestIdentifer content:content trigger:trigger1];
//5.把通知加到UNUserNotificationCenter, 到指定触发点会被触发
[[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
}];










