Firebase 推送通知不适用于 iOS [英] Firebase push notifications not working with iOS

查看:26
本文介绍了Firebase 推送通知不适用于 iOS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Firebase Cloud Messaging 实现推送通知

I want to implement push notification using Firebase Cloud Messaging

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

I have setup my project and uploaded APN certificate as explained and I am sending Test messages using fcmtoken to my real device

我在AppDelegate中的配置如下

my configuration is as follows in 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但它没有设置一个喙点似乎这部分永远不会被原谅因此消息没有来

it is supposed to see notofication arrivied but it didn't Also set a beak point It seems this part is never being excused thus message is not coming

推荐答案

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()
}

这篇关于Firebase 推送通知不适用于 iOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆