Search code examples
swiftparse-platformparse-serverback4app

Parse - Sending push notifications using cloud code (Swift)


I'm trying to set up push notifications from one user to another using Back4App which is a parse server. I have followed their guide here

the Javascript cloud code they use is below:

Parse.Cloud.define("pushsample", function (request, response) {
Parse.Push.send({
        channels: ["News"],
        data: {
            title: "Hello from the Cloud Code",
            alert: "Back4App rocks!",
        }
   }, {
        success: function () {
            // Push was successful
            response.success("push sent");
            console.log("Success: push sent");
        },
        error: function (error) {
            // Push was unsucessful
            response.error("error with push: " + error);
            console.log("Error: " + error);
        },
        useMasterKey: true
   });
});

I am updating a custom parse class called notifications within the app which I would also like to send to the user the notification is directed at. When saving this class I am grabbing the UserID which is also stored in the installation class used to send pushes. I am completely new to Javascript so am wondering if someone could tell me how to edit the above code to receive the userID from the method on the device and then run a query to send to just this user.


Solution

  • The push notification feature allows to configure options and customizing the push.

    You can send a query to update one specific user. Please, take a look at the example below:

    Parse.Cloud.define("sendPushToUser", async (request) => {
    var query = new Parse.Query(Parse.Installation);
    let userId = request.params.userId;
    query.equalTo('userId', userId);
    
    Parse.Push.send({
      where: query,
      data: {
        alert: "Ricky Vaughn was injured in last night's game!",
        name: "Vaughn"
      }
    })
    .then(function() {
      // Push was successful
    }, function(error) {
      // Handle error
    });
    

    });

    At the moment, you can read more about these options here.