ios - Firebase iOS 推送通知在首次安装时不起作用

标签 ios swift firebase apple-push-notifications firebase-cloud-messaging

当我首次安装并打开应用并接受 Apple 的通知权限警报时,我从 Firebase 收到此日志:

5.16.0 - [Firebase/InstanceID][I-IID023004] Could not update attributes of the key pair to be accessible after first unlock. update status: -25300

此后,如果我关闭应用程序或将应用程序发送到后台,我不会收到任何通知。如果我第二次打开应用程序,通知就会开始正常工作。

这是我当前的设置:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
    setupPushNotificationsHandling(application)
    return true
}

private func setupPushNotificationsHandling(_ application: UIApplication) {
    UNUserNotificationCenter.current().delegate = self
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, _) in
        guard granted else { return }

        DispatchQueue.main.async {
            application.registerForRemoteNotifications()

            FirebaseApp.configure()
            InstanceID.instanceID().instanceID { (result, _) in
                // Receive notifications from the "all" topic
                Messaging.messaging().subscribe(toTopic: "all")
            }
        }
    }
}

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    print("response \(response)")
    completionHandler()
}

最佳答案

我就是这样解决的。

  1. 在尝试订阅通知主题之前,我会等待调用委托(delegate)方法 application:didRegisterForRemoteNotificationsWithDeviceToken:
  2. 我会重试,直到调用 InstanceID.instanceID().instanceID 返回有效的设备 token 。

完成设置:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
    setupPushNotificationsHandling(application)
    return true
}

private func setupPushNotificationsHandling(_ application: UIApplication) {
    FirebaseApp.configure()

    application.registerForRemoteNotifications()

    UNUserNotificationCenter.current().delegate = self
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { (_, _) in }
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    // Receive notifications from the "all" topic
    subscribeToNotificationsTopic(topic: "all")
}

func subscribeToNotificationsTopic(topic: String) {
    // Retry until the notifications subscription is successful
    DispatchQueue.global().async {
        var subscribed = false
        while !subscribed {
            let semaphore = DispatchSemaphore(value: 0)

            InstanceID.instanceID().instanceID { (result, error) in
                if let result = result {
                    // Device token can be used to send notifications exclusively to this device
                    print("Device token \(result.token)")

                    // Subscribe
                    Messaging.messaging().subscribe(toTopic: topic)

                    // Notify semaphore
                    subscribed = true
                    semaphore.signal()
                }
            }

            // Set a 3 seconds timeout
            let dispatchTime = DispatchTime.now() + DispatchTimeInterval.seconds(3)
            _ = semaphore.wait(timeout: dispatchTime)
        }
    }
}

关于ios - Firebase iOS 推送通知在首次安装时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54489861/

相关文章:

ios - iOS 应用内购买

ios - AVURLAsset URLAssetWithURL :options: blocks main thread with remote URL?

ios - CKReference 的 CloudKit Delete Self 选项不起作用

ios - Swift:如何抑制特殊字符的解释并提供字符串文字

firebase - 未处理的异常: 'Future<QuerySnapshot>'类型不是 'QuerySnapshot'类型的子类型

javascript - 如何从 Firebase 数据库检索单个 JSON 值?

objective-c - iOS Twitter集成测试

swift - 如何从另一个类调用变量,特别是 scnscene 到 skoverlay 场景

android - 不使用 Firebase 用户 uid 的自定义 Firebase 用户身份

objective-c - 从 Xcode 项目中删除的文件,但仍可在游戏中使用