【问题标题】: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])
}

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

【问题讨论】:

标签: ios swift push-notification unusernotificationcenter


【解决方案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
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-06
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多