【问题标题】:Swift3 can't receive background FCM push notificationSwift3 收不到后台 FCM 推送通知
【发布时间】:2017-08-02 08:29:05
【问题描述】:

我是 IOS 开发新手。

我已经用谷歌搜索了 2 天。

我无法通过 FCM 接收后台推送通知。

在前台,收到但在后台,不称为委托。

检查功能->推送通知、后台模式。

我将优先级设置为 high 并将 content_available 设置为 true。

使用 swift3、ios10.3、firebase。

这是我的代码。

import UIKit
import UserNotifications
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    let gcmMessageIDKey = "gcm.message_id"

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

    Messaging.messaging().delegate = self
    if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().delegate = self

        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }

    application.registerForRemoteNotifications()
    return true
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    print(userInfo)
}
    func applicationDidBecomeActive(_ application: UIApplication)
    {
        Messaging.messaging().shouldEstablishDirectChannel = true

        application.applicationIconBadgeNumber = 0;
    }

    func applicationDidEnterBackground(_ application: UIApplication)
    {
        Messaging.messaging().shouldEstablishDirectChannel = false
        print("Disconnected from FCM.")
    }
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    print(userInfo)

    completionHandler(UIBackgroundFetchResult.newData)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("Unable to register for remote notifications: \(error.localizedDescription)")
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    print("APNs token retrieved: \(deviceToken)")

}
}

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

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

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

    print(userInfo)

    completionHandler([])
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
    }

    print(userInfo)

    completionHandler()
}
}

extension AppDelegate : MessagingDelegate {
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
    print("Firebase registration token: \(fcmToken)")
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
    print("Received data message: \(remoteMessage.appData)")
}
}

【问题讨论】:

  • 我也有这个问题。你找到解决办法了吗?

标签: ios swift firebase firebase-cloud-messaging


【解决方案1】:

在你的函数中:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)

您正在接收 deviceToken 但没有对其进行任何操作,您需要将其发送到 Firebase。

导入实例 ID:

import FirebaseInstanceID

试试这个:

func application(
   _ application:UIApplication,
   didRegisterForRemoteNotificationsWithDeviceToken deviceToken:Data)
{
   FIRInstanceID.instanceID().setAPNSToken(
      deviceToken as Data,
      type:.unknown)
}

【讨论】:

    【解决方案2】:

    在 appdelegate 中添加:

    func application(_ application: UIApplication,
                       didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Messaging.messaging().apnsToken = deviceToken as Data
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-02
      • 2022-09-27
      • 2013-01-14
      • 2017-12-09
      相关资源
      最近更新 更多