Updated 24 September 2021
In this blog, we will see how we can send push notifications using Google API. For this, we have to first create valid payload data, which we will pass in the request body and we also need the Firebase server key of our Firebase project.
Let start, you need to add the below code in a ViewController and call the below function when you want to trigger the notification.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
func sendPushNotification(){ let urlString = "https://fcm.googleapis.com/fcm/send" var request = URLRequest(url: URL(string: urlString)!) let token = "xxxxxxx" // device token on which notification has to be sent let serverkeyData = "key="+"xxxxxxxxx"//SERVER_Key_FCM request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue(serverkeyData, forHTTPHeaderField: "Authorization") let payloadData = [ "to" : token, "priority" : "high", "content_available":true, "time_to_live":30, "delay_while_idle":true, "notification" : [ "body" : "Test Body", "title": "Test", "sound": "default" ], "data" : [ "body" : "Test Body", "title": "Test", "sound": "default" ] ] as [String : Any] do{ let jsonData = try JSONSerialization.data(withJSONObject: payloadData, options: .prettyPrinted) request.httpBody = jsonData } catch { print(error.localizedDescription) } let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print("error=\(String(describing: error))") return } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { print("statusCode should be 200, but is \(httpStatus.statusCode)") print("response = \(String(describing: response))") } do { let json = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions()) as (AnyObject) print("ass",json) } catch { print("json error: \(error)") } } task.resume() } |
In the above method, we have created payloadData dictionary and passed it to the request body. We have created a variable token. The token variable stores the firebase device token. we will set the device tokens of that device on which we want to send a push notification. We also need a firebase server key which we can get from our firebase project inside the firebase console.
When the Google API is hit successfully then we can see the push notifications on the device.
Please follow the above steps in order to send push notifications through Google API to the selected device. You can also check other blogs from here. If you have any issues, query or suggestions then you can leave your issues/query/suggestion in the comment section.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.