且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Firebase推送通知不适用于iOS

更新时间:2023-01-05 18:41:36

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