我已经在 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");
}
}];
但是不显示本地通知。因为我使用了两种委托(delegate)方法,一种用于在前台显示通知,另一种方法必须在收到本地通知时调用。
在任何情况下都不会调用委托(delegate)方法。
请找出我错的愚蠢的错误
最佳答案
您看不到本地通知,因为您的应用程序可能在前台。如果您在前台,本地通知不会显示。
您的代码没问题,但我建议您进行一些更改并再次测试您的应用。
- 将触发时间增加到 10 秒。
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10 次重复:NO];
- 在
applicationDidEnterBackground
中添加了以下内容
[self localNotification];
- 让应用程序进入后台。
- 等待 10 秒,您将收到本地通知。
在前台显示通知
如果你想在你的应用程序在前台时显示通知,那么实现
在
中符合AppDelegate.h
UNUserNotificationCenterDelegate
在
AppDelegate.m
中添加如下代码-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler { completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge); }
关于ios - iOS 10 不显示本地通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43177103/