我已在 Appdelegates 中尝试过此代码。
@import UserNotifications;
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptionsUNAuthorizationOptionBadge | 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"
contentbjNotificationContent 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 方法。
请在我错的地方找出愚蠢的错误
您无法看到本地通知,因为您的应用程序可能在前台。如果您在前台,则不会显示本地通知。
您的代码没问题,但我建议您进行一些更改并再次测试您的应用。
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10 repeats:NO];
applicationDidEnterBackground
中添加了以下内容 [self localNotification];
在前台显示通知
如果您想在应用程序处于前台时显示通知,请实现
在 AppDelegate.h
UNUserNotificationCenterDelegate
在AppDelegate.m
-(void)userNotificationCenterUNUserNotificationCenter *)center willPresentNotificationUNNotification *)notification withCompletionHandlervoid (^)(UNNotificationPresentationOptions))completionHandler {
completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
}
关于ios - iOS 10 中不显示本地通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43177103/
欢迎光临 OGeek|极客世界-中国程序员成长平台 (https://ogeek.cn/) | Powered by Discuz! X3.4 |