Firebase Chat Push Notifications

Firebase chat Push Notifications

Hope someone finds this useful, it helped in my case.

Currently sending push notifications from device to device isn't possible with solution Firebase offers. If you want that type of thing, you should try OneSignal which is free and very easy to implement.

How to send push notifications for the new messages in the realtime database of firebase

If other user have push token in database first you need to access that with query and then by using AFNetworking you can send push notification to another user as shown below:

let manager = AFHTTPRequestOperationManager()
manager.requestSerializer.setValue("key=yourServerKey", forHTTPHeaderField: "Authorization")
manager.requestSerializer.setValue("application/json", forHTTPHeaderField: "Content-Type")
let sendPushForChatUrl = "https://fcm.googleapis.com/fcm/send"

let to = otherUserPushToken as! String
let notification = notificationData as! [String: AnyObject]

let param = ["to":to, "content_available":true, "priority":"high", "notification":notification] as [String : Any]

manager.post(sendPushForChatUrl,
parameters: prepareObjects(param),
success: { (operation: AFHTTPRequestOperation?,responseObject: Any?) in

print("Suceess")
print(responseObject ?? "")
} ,
failure: { (operation: AFHTTPRequestOperation?,error: Error?) in
print("Error: " + error!.localizedDescription)
print("Fail")
})

And request example will be:

{
"to":"userPushToken",
"priority":"high",
"content_available": true,
"notification":{
"notification-type":"chat",
"target":"Current User",
"title":"Current User has sent you a message",
"text": "hello1",
"badge": 5 //Badge you want to show on app icon
}
}

It will work on postman too if you want to debug it.

EDIT:

In your case below is your working code:

@IBAction func sendPushTapped(_ sender: Any) {

let manager = AFHTTPSessionManager()

manager.requestSerializer = AFJSONRequestSerializer()
manager.responseSerializer = AFJSONResponseSerializer()

manager.requestSerializer.setValue("key=AIzaSyBpJPPYSkRKH6cpDV_bpe2NQiytvPTlTcw", forHTTPHeaderField: "Authorization")
manager.requestSerializer.setValue("application/json", forHTTPHeaderField: "Content-Type")

let fcmToken = "fkXo5yZvrKc:APA91bGxj2tJKWungvA4zyOUFBp5leUghd0wczDbZSkzImjZqRfSIgEFtKCQWZL0xEPZ3xfasfJdoX_JosX87VK7ioyap1fJJcTQ9rJzlC5ahwDktTnLGVqRg-wNZZw4TVvaCemEQFs2"
let sendPushForChatUrl = "https://fcm.googleapis.com/fcm/send"

let message = ["notification-type":"chat", "target":"Current User", "title": "Hello", "text": "msg!", "sound": "default", "badge": 5] as [String : Any]
let param = ["to":fcmToken, "priority":"high", "content_available": true, "notification":message] as [String : Any]

print("Push Url :", sendPushForChatUrl)
print("Push Parameters :", prepareObjects(param))

manager.post(sendPushForChatUrl, parameters: prepareObjects(param), progress: { (NSProgress) in
print("Progress ::", NSProgress)
}, success: { (task:URLSessionDataTask, responseObject) -> Void in

print("Push response", responseObject ?? "")

}, failure: { (task:URLSessionDataTask?, error:Error) -> Void in

print("Failure: ",error.localizedDescription )

})
}

func prepareObjects(_ dict : Dictionary<String, Any>) -> NSMutableDictionary
{
let dictParameters = NSMutableDictionary()
for (key, value) in dict
{
dictParameters.setValue(value as? AnyObject, forKey: key)
}

return dictParameters
}

Firebase push notifications with node.js and flutter

What you're describing is indeed the correct approach, and is described in the Firebase documentation on accessing the registration token (this link is for Java, but the same exists on all supported platforms). From there comes this code sample:

/**
* There are two scenarios when onNewToken is called:
* 1) When a new token is generated on initial app startup
* 2) Whenever an existing token is changed
* Under #2, there are three scenarios when the existing token is changed:
* A) App is restored to a new device
* B) User uninstalls/reinstalls the app
* C) User clears app data
*/
@Override
public void onNewToken(@NonNull String token) {
Log.d(TAG, "Refreshed token: " + token);

// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
// FCM registration token to your app server.
sendRegistrationToServer(token);
}

The onNewToken here is part of the FCM API, but the sendRegistrationToServer in this code is what you are describing and something you will have to implement yourself.



Related Topics



Leave a reply



Submit