In the application, the user can follow some teams. Then, when there is an event (i.e. Match starts in few hours, score update during game play) for any of his followed teams, a push notification is sent. We have cron jobs running on servers to trigger push notification sending script. The script uses REST API of parse.
The usual and prescribed way of Parse in this situation is to use the "channel". Every Installation object has a field named "channels" (which is an array). I could save the following team codes in channels (it is called subscribing to channels in Parse terms). Then, sending push to all Installations subscribing to a channel is easy:
curl -X POST \
-H "X-Parse-Application-Id: XXX" \
-H "X-Parse-REST-API-Key: YYY" \
-H "Content-Type: application/json" \
-d '{
"channels": [
"Giants"
],
"data": {
"alert": "The Giants won against the Mets 2-3."
}
}' \
https://api.parse.com/1/push
But, our case was a bit different. We support multiple devices of a single user. So, if an user has three devices and follows Giants, then he will receive push on all three devices. There will be different Installation objects for each of the devices. And, creating duplicates of subscription (having same data in channels fields of all Installation objects of an user and keeping them synched each time something changed from any of the devices) is not a good idea.
So, what I did is, saved the preferences in a field of the User object and kept a point to owner User object from all Installation objects. Then, I did my R&D and reached a solution in following steps:
Step 1: I tested query for finding Users with "erfan" in their "pushSubscription" API call:
https://api.parse.com/1/classes/_User?limit=0&count=1&where={"pushSubscription":"erfan"}
Response:
{"results":[],"count":1}The response is as expected, I have only one user with that criteria.
Step 2: I tested query for finding all installations that have user with "erfan" in pushSubscription column API call:
https://api.parse.com/1/classes/_Installation?limit=0&count=1&where={"user":{"$inQuery":{"where":{"pushSubscription":"erfan"},"className":"_User"}}}Response:
{"results":[],"count":2}This time also the response is as expected. There are two Installations pointing to that user.
Step 3 (Final step): Now, I tried to send push using the targeting like above
API call (POST) to: https://api.parse.com/1/push with body:
{
"where":{
"user":{
"$inQuery":{
"where":{"pushSubscription":"erfan"},
"className":"_User"
}
}
},
"data": {
"alert": "Test push."
}
}
Response:
{"result":true}And it worked like a charm!
No comments:
Post a Comment