简体   繁体   English

iOS:通过url请求向firebase服务发送推送通知

[英]iOS: Sending push notification to firebase services via url request

I'm building an test app to send push notifications here is my code: 我正在构建一个测试应用程序来发送推送通知,这是我的代码:

static func sendRequestPush(){
        let json: [String: Any] = ["to": "key",
                                   "priority": "high",
                                   "notification": ["body":"Hello1", "title":"Hello world","sound":"default"]]
    let urlStr:String = "https://fcm.googleapis.com/fcm/send"
    let url = URL(string:urlStr)
    let jsonData = try? JSONSerialization.data(withJSONObject: json)
    var request = URLRequest(url: url!)
    request.httpMethod = "POST"
    request.httpBody = jsonData
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print(error?.localizedDescription ?? "No data")

            return
        }
        let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
        if let responseJSON = responseJSON as? [String: Any] {
            print(responseJSON)
        }
    }

    task.resume()
}

The problem is I don't get any response from googleapis neither the push notification. 问题是我没有从googleapis获得任何响应既不是推送通知。 I get the push notification from dash board but not from my code. 我从破折号板获得推送通知,但不是来自我的代码。

Any of you knows what I'm doing wrong? 你们中的任何人都知道我做错了什么?

I'll really appreciate your help. 我真的很感谢你的帮助。

Try the below code, It works like charm :) 试试下面的代码,它就像魅力:)

 func sendRequestPush()  {
    // create the request
    let url = URL(string: "https://fcm.googleapis.com/fcm/send")
    let request = NSMutableURLRequest(url: url!)
    request.httpMethod = "POST"
    request.setValue("key=putYourLegacyServerKeyHere", forHTTPHeaderField: "authorization")
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    let parameters = ["to": "putYourFCMToken",
                               "priority": "high",
                               "notification": ["body":"Hello1", "title":"Hello world","sound":"default"]] as [String : Any]
    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
    } catch let error {
        print(error.localizedDescription)
    }
    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)
    let dataTask = session.dataTask(with: request as URLRequest) { data,response,error in
        let httpResponse = response as? HTTPURLResponse
        if (error != nil) {
            print(error!)
        } else {
            print(httpResponse!)
        }
        guard let responseData = data else {
            print("Error: did not receive data")
            return
        }
        do {
            guard let responseDictionary = try JSONSerialization.jsonObject(with: responseData, options: [])
                as? [String: Any] else {
                    print("error trying to convert data to JSON")
                    return
            }
            print("The responseDictionary is: " + responseDictionary.description)
        } catch  {
            print("error trying to convert data to JSON")
            return
        }
        DispatchQueue.main.async {
            //Update your UI here
        }
    }
    dataTask.resume()
}

"putYourLegacyServerKeyHere" change this according to your key that you can get in FCM Console “putYourLegacyServerKeyHere”会根据您在FCM控制台中获得的密钥进行更改

"putYourFCMToken" change this with the fcm token you got in didReceiveRegistrationToken (FCM Delegate) “putYourFCMToken”使用didReceiveRegistrationToken(FCM Delegate)中的fcm标记更改此设置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM