Sam Chahine
Sam Chahine

Reputation: 620

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.

Upvotes: 2

Views: 1080

Answers (1)

sergpetrov
sergpetrov

Reputation: 1714

I have rewritten it to Kotlin using OkHttp, please check

import java.io.IOException
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import org.json.JSONObject


fun sendPushNotification(token: String, title: String, subtitle: String, body: String, data: Map<String, String> = emptyMap()) {
    val url = "https://fcm.googleapis.com/fcm/send"

    val bodyJson = JSONObject()
    bodyJson.put("to", token)
    bodyJson.put("notification",
        JSONObject().also {
            it.put("title", title)
            it.put("subtitle", subtitle)
            it.put("body", body)
            it.put("sound", "social_notification_sound.wav")
        }
    )
    bodyJson.put("data", JSONObject(data))

    val request = Request.Builder()
        .url(url)
        .addHeader("Content-Type", "application/json")
        .addHeader("Authorization", "key=$key")
        .post(
            bodyJson.toString().toRequestBody("application/json; charset=utf-8".toMediaType())
        )
        .build()

    val client = OkHttpClient()

    client.newCall(request).enqueue(
        object : Callback {
            override fun onResponse(call: Call, response: Response) {
                println("Received data: ${response.body?.string()}")
            }

            override fun onFailure(call: Call, e: IOException) {
                println(e.message.toString())
            }
        }
    )
}

P.S. val client = OkHttpClient() is just for example, you shouldn't create it every time. OkHttpClient should be shared, it performs best when you create a single OkHttpClient instance and reuse it for all of your HTTP calls.

Upvotes: 1

Related Questions