我在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");
}
}];
}
但不显示本地通知。因为我使用了两个Delegates方法,一个用于前台的当前通知,一个方法必须在收到本地通知时被调用。
在任何场景中都不会调用Delegates方法。
请找到我错了的傻错误
答案 0 :(得分:5)
您无法看到本地通知,因为您的应用程序可能位于前台。如果您在前台,则不会显示本地通知。
您的代码没问题,但我建议您进行一些更改&再次测试您的应用。
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10 repeats:NO];
applicationDidEnterBackground
[self localNotification];
在前景上显示通知
如果您想在应用程序处于前台时显示通知,请执行
在UNUserNotificationCenterDelegate
AppDelegate.h
在AppDelegate.m
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
}
答案 1 :(得分:0)
如果您处于前台,将调用您的委托方法,但不会显示可视通知。如果您真的想在前台显示通知,可以使用以下内容: