Search code examples
iosfirebaseswift3push-notificationfirebase-cloud-messaging

send push notification to device directly from a device swift 3


Is there any way to send push notification from a device to device directly using https://fcm.googleapis.com/fcm/send.

My code:

func sendPushNotification(toUser: String, message: String) {
    let urlString = "https://fcm.googleapis.com/fcm/send"
    let url = NSURL(string: urlString)!
    let paramString  = "to="

    let request = NSMutableURLRequest(url: url as URL)
    request.httpMethod = "POST"
    request.httpBody = paramString.data(using: String.Encoding.utf8)!
    request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

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

Solution

  • let paramString  = ["to" : FCM_ID/UDID, "notification" : ["title" : NOTIFICATION_TITLE, "body" : NOTIFICATION_BODY], "data" : ["user" : USER_ID, "image" : IMAGE_URL, "extrainfo" : ANY_STRING]]
    

    just replace your line with this one and push notification should deliver.

    Read more about it here... https://firebase.google.com/docs/cloud-messaging/server