iOS10 之后使用才有效果
1.在 AppDelegate.m 文件里面添加下面的方法。
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler { completionHandler(UNNotificationPresentationOptionBadge |UNNotificationPresentationOptionSound |UNNotificationPresentationOptionAlert); }
2. 对content添加属性的方式实现。
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init]; content.body = @"本地通知--content"; content.title = @"本地通知--title"; content.sound = [UNNotificationSound defaultSound]; content.badge = @(msgArr.count); //10之后的系统可以设置在前台显示 [content setValue:@(YES) forKeyPath:@"shouldAlwaysAlertWhileAppIsForeground"]; // 触发模式 UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:1 repeats:NO]; // 创建本地通知 NSString *requestIdentifer = [NSString stringWithFormat:@"TestRequestww1%u",arc4random() % 1000]; UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requestIdentifer content:content trigger:trigger]; //把通知加到UNUserNotificationCenter, 到指定触发点会被触发 [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { }];