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

Posted

技术标签:

【中文标题】应用程序打开时如何获得推送通知?【英文标题】:how to get push notification when app is open? 【发布时间】:2019-06-11 10:58:23 【问题描述】:

我正在开发 swift 4.2。当应用程序处于后台时我会收到通知,但当应用程序处于活动状态时我没有收到通知。

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

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

【问题讨论】:

为什么你认为你不明白?它只是没有显示。见***.com/questions/30852870/… 【参考方案1】:

您需要在您的 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])

【讨论】:

你最开心了:)【参考方案2】:

使用上述代码更新此代码

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
    

【讨论】:

以上是关于应用程序打开时如何获得推送通知?的主要内容,如果未能解决你的问题,请参考以下文章