本地通知在iOS 10中未显示

3
我已经在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");
    }
}];

但本地通知未显示。由于我使用了两个代理方法,一个用于在前台呈现通知,另一个必须在收到本地通知时调用的方法。

这些代理方法在任何情况下都没有被调用。

请找出我犯的愚蠢错误。

2个回答

9

由于您的应用程序可能在前台运行,因此您无法看到本地通知。如果您处于前台,则不会显示本地通知。

您的代码可以正常运行,但我建议您进行一些更改并再次测试您的应用程序。

  1. 将触发时间增加到10秒。UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10 repeats:NO];
  2. applicationDidEnterBackground中添加以下内容。

[self localNotification];

  1. 使应用程序进入后台。
  2. 等待10秒钟,您将收到本地通知。

在前台显示通知

如果要在应用程序在前台运行时显示通知,则需要实现:

  1. Conform UNUserNotificationCenterDelegate in AppDelegate.h

  2. Add following code in AppDelegate.m

    -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
    }


添加:如果您不想更改静默推送通知,则应添加条件来排除使用它们的标识符进行自定义通知:if(notification.request.identifier == "CustomNotification") { completionHandler([.alert, .badge, .sound]) } else { completionHandler([]) } - Mu Sa

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接