Harids
Harids

Reputation: 31

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

I made a chat app using firebase realtime database and I'm getting the messages also. But I want to integrate the push notification also. It should send push notification to the users when they got a message. Could it be possible?

Upvotes: 1

Views: 1273

Answers (1)

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

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
}

Upvotes: 2

Related Questions