Parse Server Tutorial with iOS

In this tutorial you will learn how to setup your own Parse Server solution hosted on Heroku and connect it with your iOS app. By Ron Kliffer.

Leave a rating/review
Save for later
Share
You are currently viewing page 2 of 3 of this article. Click here to view the first page.

Configure the iOS app

At last you get to dive back into the comfortable familiarity of Swift. The starter app doesn’t have the correct configuration to use Parse SDK with Parse Server.

Pull up the app in Xcode, open AppDelegate.swift and look for the line below in application(_:didFinishLaunchingWithOptions:):

let configuration = ParseClientConfiguration {
      $0.applicationId = "APPLICATION_ID"
      $0.server = "SERVER_URL"
    }
    Parse.initialize(with: configuration)

Replace it with the block below, substituting APPLICATION_ID with your app’s bundle identifier:

let configuration = ParseClientConfiguration {
  $0.applicationId = "com.razeware.ParseTutorial"
  $0.server = "http://localhost:1337/parse"
}
Parse.initialize(with: configuration)

The ParseClientConfiguration object represents the configuration the Parse SDK should use to connect with the server. It lets you create configuration variables for various connection parameters, including your Application ID, Server URL and so on.

This configuration object is passed to initialize(with:), which then sets up the Parse SDK before connecting to the server.

Build, run and log in. Tap the Upload button and choose an image from your phone or Simulator’s stock images.

Write a short comment and tap Send. To double-check that you’re writing to the “online” database, try these two sanity checks:

  1. Go to the WallPost collection on the mLab website and look for the image you just sent.
  2. Delete the app from your phone or Simulator. Then build and run, log in and check if you can retrieve the image and comment from the Mongo database.

parse server tutorial

If it’s there, you’re ready to move the Parse Server to Heroku’s web hosting service.

Deploy the Parse Server to Heroku

In order to manage Heroku apps from Terminal, you’ll need to download and install the Heroku Toolbelt from the Heroku website. It’s a command line interface tool for creating and managing Heroku apps.

Note: Heroku is also available in Homebrew, however, it’s a standalone version of the Heroku Toolbelt that doesn’t include all the required components.

If you don’t already have a Heroku account, please visit the Heroku sign up page and do the needful.

Next, authenticate against Heroku by running the following command inside the local Parse Server directory:

$ heroku login

The Heroku platform uses git for deploying applications. When you create an application on Heroku, it associates a new git remote, typically named heroku, with the local git repository for your application. Since the Parse project was cloned from GitHub, a local git repository exists. All you need to do is initialize Heroku, and push to its remote.

From the Parse project directory, create an application on Heroku and push your source code to the Heroku server:

$ heroku create
heroku-cli: Installing core plugins... done
Creating app... done, stack is cedar-14
https://intense-chamber-52549.herokuapp.com/ | https://git.heroku.com/intense-chamber-52549.git

Notice a Heroku service was created for you (in my case it was at: https://intense-chamber-52549.herokuapp.com).

Next, commit your changes, and push the local Parse Server to the newly created Heroku service with the following command:

$ git add .
$ git commit -m "Commit with my custom config"
$ git push heroku master

Paste the URL you made with the create command into a web browser and you should see the same message as before when you tested the server locally:

I dream of being a web site.

Now you need to test if that shiny new Heroku service still responds to GET requests. Remember to replace <myAppId> with your app’s Bundle Identifier, as well as your Heroku server URL:

$ curl -X GET \
-H "X-Parse-Application-Id: <myAppId>" \
-H "Content-Type: application/json" \
-d '{}' \
https://<your URL>.herokuapp.com/parse/classes/WallPost

This is a similar curl as before when you were executing against a local server. This command goes against the remote server.

You should see the JSON version of the wall post record you created inside the iOS app:

{
  "results": [
    {
      "objectId": "a8536MK9nC",
      "image": {
        "__type": "File",
        "name": "57eb6f36cd8bcce8141dc5ccca3072c0_image.bin",
        "url": "http:\/\/afternoon-harbor-27828.herokuapp.com\/parse\/files\/" \
          "jJ5Ds5h0eXWYhv7DGWYIrfLQTn2rjB0okakvo3LH\/57eb6f36cd8bcce8141dc5cc" \
          "ca3072c0_image.bin"
      },
      "user": {
        "__type": "Pointer",
        "className": "_User",
        "objectId": "SLPlVVfsvx"
      },
      "comment": "great pic!",
      "updatedAt": "2016-03-14T17:36:20.849Z",
      "createdAt": "2016-03-14T17:36:20.849Z"
    }
  ]
}

It works! You’ve just set up your Parse app and database to the cloud, and that’s an accomplishment!

Implement Basic Push Notifications

Note: If you’re setting up push notifications on iOS for the first time and want to go through all the steps outlined below, you’ll need to head to the Push Notifications Tutorial and work through it until you’ve generated and downloaded the certificate.

When initializing Parse Server, you need to set up an additional push configuration. Inside the Parse Server directory, open the index.js file and add the following code block after the serverURL line:

push: {
  ios: [
    {
      pfx: 'cert.p12',
      bundleId: 'com.example.ParseTutorial',
      production: false
    }
  ]
},

The certificate cert.p12 is the one you exported from the Push Notifications Tutorial (it may be named WenderCastPush.p12). The bundleId should be the one you previously created in the Push Notifications Tutorial. You also need to change the Bundle Identifier for the app as well to match in Xcode.

production should be false if you’re using a development certificate, and true if you’re using a production certificate.

Additionally, add a Master Key to index.js. You can use any arbitrary string, but keep it secret!:

// Replace this
masterKey: process.env.MASTER_KEY || '',

// With the value of your app's Master Key completed:
masterKey: process.env.MASTER_KEY || '<your app's Master Key>',

Your next step is to put the certificate inside the local Parse Server directory, so it can be sent to the Heroku service. After doing that, run these commands in Terminal:

$ git add .
$ git commit -m "added certificate"
$ git push heroku master

Switch back to Xcode, open AppDelegate.swift and find the application(_:didFinishLaunchingWithOptions:) method. Replace this:

$0.server = "http://localhost:1337/parse"

With this (using your Heroku URL):

$0.server = "https://afternoon-harbor-27828.herokuapp.com/parse"

Now you’ll register your app for remote push notifications.
Go to the top of AppDelegate and add the following line:

import UserNotifications

Add the following lines to the end of application(_: didFinishLaunchingWithOptions:):

//1
let userNotificationCenter = UNUserNotificationCenter.current()
userNotificationCenter.delegate = self

//2
userNotificationCenter.requestAuthorization(options: [.alert, .badge, .sound]) { accepted, error in
  guard accepted == true else {
    print("User declined remote notifications")
    return
  }
//3
  application.registerForRemoteNotifications()
}

Here’s a step-by-step explanation of the above code:

  1. Get the UNUserNotificationCenter singleton object, and assign self as the delegate
  2. Request notification authorization for types .alert, .badge and .sound.
  3. If user grants authorization, register the application for remote notifications

Next, you need to implement UNUserNotificationCenterDelegate. Add the following to the bottom of AppDelegate.swift:

extension AppDelegate: UNUserNotificationCenterDelegate {
  
  func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler:
                                @escaping (UNNotificationPresentationOptions) -> Void) {
    PFPush.handle(notification.request.content.userInfo)
    completionHandler(.alert)
  }
}

When your app receives a remote notification from the APNs, this delegate method is called. Here you pass the notification’s userInfo for the Parse SDK to handle its presentation.

Finally, you need to store the device token. Add the following below application(_:didFinishLaunchingWithOptions:):

// 1
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  let installation = PFInstallation.current()
  installation?.setDeviceTokenFrom(deviceToken)
  installation?.saveInBackground()
 }
// 2
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
  if (error as NSError).code == 3010 {
    print("Push notifications are not supported in the iOS Simulator.")
  } else {
    print("application:didFailToRegisterForRemoteNotificationsWithError: %@", error)
  }
}

Here’s an explanation of what you just added:

  1. This method is called once the app successfully registers with the APNs (Apple Push Notification service). The device will only act on notifications that have the specified deviceToken.
  2. When the APNs can’t complete device registration due to an error, this method gets called with error information, so your app can determine why registration failed.

Before you build and run, make sure Push Notifications is turned on it the target’s Capabilities tab. If it’s off, press the toggle to turn it on. You might see the following:

capabilities

If that is the case, press Fix Issue to let Xcode handle it for you.

Build and run the app on a device because push notifications aren’t supported in iOS Simulator. To test, run this command in Terminal — remember to replace the Application ID, Master Key and server URL:

curl -X POST \
-H "X-Parse-Application-Id: <YOUR_APP_ID>" \
-H "X-Parse-Master-Key: <YOUR_MASTER_KEY>" \
-H "Content-Type: application/json" \
-d '{
  "where": {
    "deviceType": "ios"
  },
  "data": {
    "alert": "Hello, Parse!"
  }
}' https://<YOUR_SERVER_URL>.herokuapp.com/parse/push

If all went well, you should get a notification on your screen as shown below:

parse server tutorial