5

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. 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.

KENdi
  • 7,576
  • 2
  • 16
  • 31
user2924482
  • 8,380
  • 23
  • 89
  • 173

1 Answers1

3

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

"putYourFCMToken" change this with the fcm token you got in didReceiveRegistrationToken (FCM Delegate)

R. Mohan
  • 2,182
  • 17
  • 30
  • @R Mohan, I tried your solution but I'm getting `RL: https://fcm.googleapis.com/fcm/send } { Status Code: 401, Headers {`. I using the token I'm getting from the delegate `putYourFCMToken`. and the `Legacy server key` from the dash board. Do you know why I'm getting the `401` ? – user2924482 Jul 04 '18 at 19:37
  • @user2924482 the Status code 401 is authentication error. If you are not adding the Content-Type in request it will come or if you are missing any parameters such priority or notification keys it will give 401. Check the parameters you entered are correct. – R. Mohan Jul 05 '18 at 07:41
  • Is there any way to implement this same functionality directly using firebase sdk instead of using post url? – Yogendra Patel Feb 15 '21 at 12:39