打开应用程序时如何获取推送通知?

时间:2019-06-11 10:58:23

标签: ios swift push-notification unusernotificationcenter

我正在使用Swift 4.2。当应用程序处于后台运行时,我会收到通知,但是当应用程序处于活动状态时,我不会收到通知。

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.alert, .badge, .sound])
}

我想知道如何在应用打开时得到通知

2 个答案:

答案 0 :(得分:0)

您需要在AppDelegate类中确认UNUserNotificationCenterDelegate;

import UserNotifications

class AppDelegate : UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate

   func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

      UNUserNotificationCenter.current().delegate = self

   }

然后您可以在ViewController类中调用此函数,不要忘记再次在ViewController中导入UserNotifications;

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) 
{
    completionHandler([.alert, .badge, .sound])
}

答案 1 :(得分:0)

使用上述代码更新此代码

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler:
        @escaping (UNNotificationPresentationOptions) -> Void) {
        print("Handle push from foreground")
        print("\(notification.request.content.userInfo)")
        completionHandler([.alert, .badge, .sound])

        return
    }