Send using Cloud Code and Swift

Step 1: Set your app to receive push notifications:

Follow the Push Notification with DashBoard guide

Step 2: Add channel to installation:

To send notifications via cloud code, you have to send via a channel, so register the installation in a channel:

let currentInstallation = PFInstallation.current()
currentInstallation.addUniqueObject("channelName", forKey: "channels")
currentInstallation.saveInBackground()

Now the installation is registred in the channel called channelName.

 

Step 3: Make the .js file with the code for send the notification:

For work with cloud code, we need to code in JavaScript. Let’s make a code for send a notification with the message “Hello from the Cloud Code” to the channelName channel:

Parse.Cloud.define("pushsample", function (request, response) {
    Parse.Push.send({
        channels: ["channelName"],
        data: {
            title: "Hello!",
            message: "Hello from the Cloud Code",
        }
   }, {
        success: function () {
            // Push was successful
            response.sucess("push sent");
        },
        error: function (error) {
        // Push was unsucessful
        response.sucess("error with push: " + error);
        },
        useMasterKey: true
   });
});

 

Step 4: Upload the .js file to the back4app cloud:

Go to your app dashboard, click on “Cloud Code”:

back4appdashboard

Next, click on “Choose file”, select the .js file, then click on “Save”:

cloudcode

 

Step 5: Call it from the app, or from a REST API:

To call a cloud code function from the app, just use the following code:

PFCloud.callFunctionInbackground("functionName", withParameters: [functionParameters]) {
     (response, error) in
     if error == nil {
         // Do something with response
     } else {
         // Handle with error
     }
}

To call a cloud code function from a REST API, use the code below:

curl -X POST -H "X-Parse-Application-Id: ${APPLICATION_ID}" \
-H "X-Parse-REST-API-Key: ${REST_API_KEY}" \
-H "Content-Type: application/json" \
-d ‘{ // Put the function parameters here in JSON format }’ \
https://parseapi.back4app.com/functions/functionName