Monday, 22 August 2022

Sending FCM Push Notification in Kotlin Client App - Firebase Cloud Messaging

I'm trying to find a way to send a request to FCM inside Kotlin, but I'm not able to find any solution.

This is how I did it in Swift:

func sendPushNotification(to token: String, title: String, subtitle: String, body: String, data: [String: String] = [:]) {
        let urlString = "https://fcm.googleapis.com/fcm/send"
        let url = NSURL(string: urlString)!
        let paramString: [String : Any] = [
            "to" : token,
                                           
            "notification" : [
                "title" : title,
                "subtitle": subtitle,
                "body" : body,
                "sound": "social_notification_sound.wav"
            ],
                                          
            "data" : data
        ]

        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={key}", forHTTPHeaderField: "Authorization")
        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()
    }

I'm pretty new to Kotlin so I'm not sure what to do. I've installed "Retrofit" but so far I've failed. Am I able to use FirebaseMessagingService() to send a notification to a token I proved, with the title, subtitle, body & sound in Kotlin?

If so, what would that function look like?

Thank you in advanced.



from Sending FCM Push Notification in Kotlin Client App - Firebase Cloud Messaging

No comments:

Post a Comment