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

how to get push notification when app is open?

我正在研究 swift 4。2.I 当应用程序处于后台时我收到通知,但当应用程序处于活动状态时我没有收到通知。

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

我想知道如何在应用程序打开时收到通知

您需要在 AppDelegate 中确认 UNUserNotificationCenterDelegate class;

import UserNotifications

class AppDelegate : UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate

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

      UNUserNotificationCenter.current().delegate = self

   }

然后你可以在你的ViewControllerclass中调用这个函数,不要忘记在ViewController;

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

用上面提到的代码更新此代码

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
    }