【问题标题】:Firebase push notifications not working with iOSFirebase 推送通知不适用于 iOS
【发布时间】:2020-05-22 13:41:40
【问题描述】:

我想使用 Firebase 云消息传递实现推送通知

我已经按照说明设置了我的项目并上传了 APN 证书 我正在使用fcmtoken 向我的真实设备发送测试消息

我在AppDelegate中的配置如下

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure()
        registerForPushNotifications(app: application)
        return true
    }

    func registerForPushNotifications(app: UIApplication) {
        UNUserNotificationCenter.current().delegate = self
        Messaging.messaging().delegate = self

        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { (authorized, error) in
            if let error = error {
                print(error.localizedDescription)
                return
            }
            if authorized {
                print("authorized")
                DispatchQueue.main.async {
                  UIApplication.shared.registerForRemoteNotifications()
                }
            } else {
                print("denied")
            }
        }
        app.registerForRemoteNotifications()
    }

    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("Firebase registration token: \(fcmToken)")
        let dataDict:[String: String] = ["token": fcmToken]
         NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
         // TODO: If necessary send token to application server.
         // Note: This callback is fired at each app startup and whenever a new token is generated.
    }

    func application(_ application: UIApplication,
        didReceiveRemoteNotification notification: [AnyHashable : Any],
        fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print("notofication arrivied")
      if Auth.auth().canHandleNotification(notification) {
        completionHandler(.noData)
        return
      }
      // This notification is not auth related, developer should handle it.
    }

它应该看到notofication arrivied,但它没有也设置了一个喙点似乎这部分永远不会被原谅,因此消息不会来

【问题讨论】:

  • @Eilon 从 FCM 控制台使用我的设备的 fcmToken 我使用此 firebase.google.com/docs/cloud-messaging/ios/… 发送测试消息
  • 是只有“didReceiveRemoteNotification”没有被调用还是根本没有收到通知?
  • @KonstantinOznobihin 是的,它只是没有被调用的那个
  • 您是否在 Firebase 控制台/项目设置/云消息传递中添加了 APNs 身份验证密钥或证书?
  • @KonstantinOznobihin 是的,我检查过它没有解决我的问题

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


【解决方案1】:
func sendPushNotification(to token: String, title: String, body: String, userInfo: [String: Any]) {
    let payload: [String: Any] = ["title": title, "body": body, "sound": "sound.caf"]
    let paramString: [String: Any] = ["to": token, "notification": payload, "data": userInfo]
    
    let urlString = "https://fcm.googleapis.com/fcm/send"
    let url = NSURL(string: urlString)!
    let request = NSMutableURLRequest(url: url as URL)
    request.httpMethod = "POST"
    request.httpBody = try? JSONSerialization.data(withJSONObject:paramString, options: [.prettyPrinted])
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("key=\(Keys.gmsServerKey)", forHTTPHeaderField: "Authorization")

    let task =  URLSession.shared.dataTask(with: request as URLRequest)  { (data, response, error) in
        do {
            if let data = data {
                if let object  = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: Any] {
                    NSLog("Received data: \(object))")
                }
            }
        } catch let err as NSError {
            print(err.debugDescription)
        }
    }
    task.resume()
}

【讨论】:

  • 总是建议对给定的代码提供解释,你写的越详细,答案就越有用
【解决方案2】:

除非你启用了 Swizzling,否则我在你的 AppDelegate 中看不到这个

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

此代码将您的 APNs 设备令牌映射到 FCM 令牌,这是必要的,因为 APNs 令牌是您发送推送通知的唯一方式。

【讨论】:

    猜你喜欢
    • 2018-05-25
    • 2021-03-31
    • 2017-01-22
    • 2017-04-09
    • 2016-11-29
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 2012-04-12
    相关资源
    最近更新 更多