【问题标题】:How to Receive Push Notifications in Foreground iOS Swift 3.0?如何在前台 iOS Swift 3.0 中接收推送通知?
【发布时间】:2017-09-20 05:19:44
【问题描述】:

我想以前台状态显示 iOS 8.0 的推送通知。我在后台状态下收到通知,但不是在前台状态下。

【问题讨论】:

标签: swift3 ios8 apple-push-notifications


【解决方案1】:
extension AppDelegate: UNUserNotificationCenterDelegate {

    // Receive displayed notifications for iOS 10 devices.
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        completionHandler(UNNotificationPresentationOptions.alert)

        //completionHandler([.alert,.badge])
        let userInfo = notification.request.content.userInfo
        if let messageID = userInfo[gcmMessageIDKey] {

        }

        // Print full message.
        print(userInfo)
        completionHandler([])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response:UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo

        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
            print("Message ID: \(messageID)")
        }

        // Print full message.
        print(userInfo)
        completionHandler()
    }
}

【讨论】:

  • completionHandler(UNNotificationPresentationOptions.alert) 是您所需要的。
  • 那是 iOS10 的。这个问题是关于 iOS 8 的。见here
  • @Honey 你能告诉我按照我的代码我会怎么做
  • @CtanLi 也因为我已经在 iOS 10 中收到了我想要在 iOS 8 中的前台通知