iOS 10中不显示本地通知

Mad*_*rea 2 objective-c ios uilocalnotification

我在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;
            }
    }];
Run Code Online (Sandbox Code Playgroud)

并且此代码触发了本地通知

-(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");
    }
}];
Run Code Online (Sandbox Code Playgroud)

}

但不显示本地通知.因为我使用了两个Delegates方法,一个用于前台的当前通知,一个方法必须在收到本地通知时调用.

在任何方案中都不会调用Delegates方法.

请找到我错了的傻错误

aas*_*sya 5

您无法看到本地通知,因为您的应用程序可能位于前台.如果您在前台,则不会显示本地通知.

您的代码没问题,但我建议您进行一些更改并再次测试您的应用.

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

[self localNotification];

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

在前景上显示通知

如果要在应用程序处于前台时显示通知,请执行

  1. 符合UNUserNotificationCenterDelegateAppDelegate.h

  2. 在中添加以下代码 AppDelegate.m

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