我已经在Appdelegates中尝试过这段代码。
@import UserNotifications;
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!error) {
NSLog(@"request authorization succeeded!");
center.delegate = self;
}
}];
这段代码触发了本地通知
-(void)localNotification{
NSLog(@"local notification fired");
UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
objNotificationContent.title = @"local notificatin";
objNotificationContent.body = @"message";
objNotificationContent.sound = [UNNotificationSound defaultSound];
/// 4. update application icon badge number
objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);
// Deliver the notification in five seconds.
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger
triggerWithTimeInterval:0.3 repeats:NO];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"three"
content:objNotificationContent trigger:trigger];
/// 3. schedule localNotification
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (!error) {
NSLog(@"Local Notification succeeded");
}
else {
NSLog(@"Local Notification failed");
}
}];
但本地通知未显示。由于我使用了两个代理方法,一个用于在前台呈现通知,另一个必须在收到本地通知时调用的方法。
这些代理方法在任何情况下都没有被调用。
请找出我犯的愚蠢错误。
if(notification.request.identifier == "CustomNotification") { completionHandler([.alert, .badge, .sound]) } else { completionHandler([]) }
- Mu Sa