神刀安全网

Migrating Away From Parse

Migrating Away From Parse Parse , one of the most popular backend solutions for mobile apps, recently announced it’s shutting down its service. Naturally, this caused confusion amongst developers because it was surprising and disruptive — in a bad way. Anything built on the platform will need significant reworking, or it’ll cease to function.

The good news is that there are options, and the team here has analyzed and compared several viable alternatives to Parse .

One question remains: Should developers take the same risk and depend on third-party backend providers?

The truth is, anything outside of building and hosting your own backend service carries some risk because services come and go. When you think about it, a DIY option carries risks too — you might find it’s not worth it or later decide it’s too much of a hassle to keep up.

If you’ve got Parse on any of your apps, then it’s up to you to analyze the options and decide how to move forward in a Parseless world.

This tutorial will explore one option: setting up and hosting your very own Parse Server.

Note: This tutorial assumes you know the basics of developing iOS apps using the Parse service. If you’re new to this topic, check out the Parse Tutorial: Getting Started with Web Backends tutorial first.

Getting Started

First, you need an existing iOS app that uses Parse so you can follow the steps in this tutorial. Feel free to use your own demo app, or download this Parse Starter project . It’s set up to work with Swift 2.2 , iOS 9 and includes the latest Parse SDK (at the time of writing v1.12.0 ).

Build and run the project in Xcode to see the following:

Migrating Away From Parse

Meet the Parse Server

In this tutorial, you’ll learn how to install your own Parse Server that can be maintained through the Parse SDK. It’s open source, thus (almost) guaranteeing it’ll never cease to exist. It can be hosted by all major web service providers, such as Heroku, Amazon AWS or Azure.

There are however, a few features from Parse.com that have not been implemented on Parse Server , such as jobs, analytics and config. Moreover, with Parse Server, you do all of the work of installing and hosting the service either locally or in the cloud.

Parse made all the necessary tools available to help developers transition away from its service by January 28, 2017 : an open source Parse Server , Migration guide, Push Notification guide and a Parse Dashboard for local development.

Parse further recommends that you use mLab (formerly known as MongoLab ) and Heroku to host the database and server, respectively.

The minimum requirements to install Parse Server are:

  • Node 4.3
  • MongoDB version 2.6.X or newer
  • Python 2.x
  • For deployment, Heroku Toolbelt

The MongoDB requirements for Parse Server are:

  • About 10 times the space you’re currently using with Parse, because the old service compressed your content heavily .
  • The failIndexKeyTooLong parameter must be set to false to accommodate indexed fields larger than 1024 bytes in size and collections larger than 1 million documents.
  • An SSL connection — although it’s not required, it’s strongly recommended.
  • For minimal latency, host your MongoDB servers in the US-East region .

Migrating the Database and Installing Parse Server

Creating a New Database

Go to the mLab website and create an account if you don’t have one already, and then watch for the confirmation email that will let you activate your new account. Once activated, click the Create New button. Choose Amazon AWS, US East, Single-node and Sandbox — these are the recommended free options:

Migrating Away From Parse

Your database name can be anything, but for now, just use tutorial-app . Click on Create New MongoDB Deployment and wait for your new database to be created.

Next, select tutorial-app and go to Users / Add database user . Enter a username and password then click Create . Save your Database URI somewhere that’s easy to reference, because you’ll need it several times throughout this tutorial. It should look similar to the one below, but your database ID will be unique:

mongodb://<dbuser>:<dbpassword>@ds017678.mlab.com:17678/tutorial-app

Migrating the Parse Database to mLab

Go to the Parse dashboard [FPE TODO: Check that this is the correct link] and find your app. Click App Settings and then the red Migrate button under General . On the next screen, paste your Database URI, and then click Begin the Migration ; ignore this warning for now:

We strongly suggest you enable SSL on your database and use the URL option 'ssl=true'.

Note: If you don’t see the red Migrate button, then check if you’re using the new Parse Dashboard . The old Parse Dashboard does not have the red Migrate button. [FPE TODO: Is this a fairly self-explanatory, or should this note also explain how to check which dashboard you’re on?]

Once migration finishes, a warning will appear. Click Finalize after the warning: "This action is irreversible!" . Once the migration completes successfully, your general page should look like this:

Migrating Away From Parse

Return to the mLab website to look for your migrated database. Under MongoDB Deployments , you should see the database you created: ds017678/tutorial-app .

Note: If you don’t see MongoDb Deployments , click the Home link in the top-left corner to make it show itself.

Click on the database to see all of its collections. In particular, take note of the Player class since that is where you saved data when you built your Parse starter app in the previous tutorial. [FPE TODO: previous tutorial? Huh?]

Click on the Player class and notice that your old records are all there! If you didn’t go through the previous Parse tutorial, then you obviously won’t see any data there. [FPE TODO: What tutorial? Is this referencing the tutorial linked at the beginning?]

You’ll write new records to this database soon, and they’ll appear as a new collection.

Migrating Away From Parse

Install the Prerequisites

Open a terminal window and run through the below steps to make sure the required support is in place.

Homebrew

If you don’t have Homebrew , enter this command:

$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

If you already have Homebrew, make sure it’s up to date by entering this command:

$ brew update

MongoDM

Next, install MongoDB — this can take a few minutes:

$ brew install mongodb --with-openssl

Create a local MongoDB database by running the following:

$ mkdir -p /data/db

If you don’t have permission to write files at the root of your hard drive, then place sudo in front of mkdir and try again.

Now you just need to verify that you have the required MongoDB version, v2.6.X or newer:

$ mongo MongoDB shell version: 3.2.3 connecting to: test Welcome to the MongoDB shell.

Press Control + D to quit MongoDB.

Note: If your Mongod daemon isn’t already running, then use the following command after installing MongoDB to allow connections to your local MongoDB daemon.

$ mongod --config /usr/local/etc/mongod.conf

Python

It’s usually installed on all major OS versions, but check if you have it first:

$ python -V Python 2.7.10

If you get a no , install Python by running this:

$ brew install python

Node

Install the latest version of Node:

$ brew install node

Confirm that you have the required version — v4.3 or newer:

$ node --version V4.3.1

Installing the Parse Server

To make life a little easier for developers, Parse created a local version of its server and pushed it to Github. Make a clone of it on your system:

$ git clone https://github.com/ParsePlatform/parse-server-example.git Parse

Change the directory to the freshly cloned Parse directory:

$ cd Parse

Install Parse Server in this directory:

$ npm install

Start Parse Server:

$ npm run start

Check if it was successful by copying and pasting this address in your browser:

$ http://localhost:1337

Migrating Away From Parse

Well, at least it dreams of being something. Rather progressive for a server, don’t you think? :]

Next, you have to configure your Parse Server to get it talking to your mLab database. Replace the default database string inside the index.js file with your MongoDB database URI:

// Replace this var databaseUri = process.env.DATABASE_URI || process.env.MONGOLAB_URI;   // With this var databaseUri = 'mongodb://<dbuser>:<dbpassword>@ds017678.mlab.com:17678/tutorial-app';

Now that you’ve wired it up, you need to test if the Parse Server is talking to the remote database. Remember to insert your Application ID from the Parse.com dashboard:

$ curl -X GET / -H "X-Parse-Application-Id: <myAppId>" / -H "Content-Type: application/json" / -d '{}' / http://localhost:1337/parse/classes/Player

The server should return any old records:

{   "results": [     {       "objectId": "cZU7xfUNrX",       "createdAt": "2016-02-25T22:54:02.679Z",       "updatedAt": "2016-02-25T22:54:02.679Z",       "Name": "John",       "Score": 810     },     {       "objectId": "sT4diOLqN3",       "createdAt": "2016-02-25T22:52:01.139Z",       "updatedAt": "2016-02-25T22:52:01.139Z",       "Name": "John",       "Score": 1230     },     {       "objectId": "vRW6MAg3bX",       "createdAt": "2016-02-25T22:54:35.189Z",       "updatedAt": "2016-02-25T22:54:35.189Z",       "Name": "Sally",       "Score": 2400     }   ] }

You now have a functioning Parse Server complete with real data.

Migrating Away From Parse

Configure the iOS app

Finally, you get to see some Swift ! To use Parse SDK with Parse Server, the starter app needs the right server URL.

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

Parse.setApplicationId("--AppID Goes Here--", clientKey: "--ClientKey Goes Here--")

Replace it with the block below, substituting your Application ID and Client Key from the Parse Dashboard:

let configuration = ParseClientConfiguration {   $0.applicationId = "YOUR_APP_ID"   $0.clientKey = "YOUR_CLIENT_KEY"   $0.server = "http://localhost:1337/parse" } Parse.initializeWithConfiguration(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, Client Key, Server URL and so on.

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

Before you build and run the app, make sure you still have the username and password from the previous Parse tutorial. If you don’t have credentials, or cannot remember them, you can easily create new credentials on the User page inside the Parse Dashboard . Just click the + sign under the objectID column, then enter a new username and password:

Migrating Away From Parse

Build and run the app, then login using your credentials. After a successful login, tap the Upload button and choose an image from your phone or simulator’s stock images. Next, write a short comment and tap Send . To really make sure you’re writing to the “online” database, you can do two checks: first, go to the WallPost collection on the mLab website and notice the image you just sent. Second, delete the app from your phone or simulator. Build and run the app, login and see that you’re still retrieving the image and comment from the Mongo database:

Migrating Away From Parse

Excellent! You’re now ready to move the Parse Server to Heroku’s web hosting service.

Deploying the Parse Server to Heroku

In order to manage Heroku apps from the terminal, you’ll need to download and install the Heroku Toolbelt from the Heroku web site . Heroku Toolbelt is a command line interface tool for creating and managing Heroku apps.

Note: You could have attempted to install using Homebrew , however Homebrew’s version is a standalone version of the Heroku Toolbelt and does not include all the required Heroku components.

If you don’t already have a Heroku account, please visit the Heroku Signup page and register for an account. Next, authenticate against Heroku using 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. Next, initialize this directory as a Github repository using the following commands:

$ git init $ git add -A $ git commit -m "first commit"

Next, create an application on Heroku and push your source code to the Heroku server:

$ heroku create

Notice a Heroku service was created for you (in my case it was at: https://afternoon-harbor-27828.herokuapp.com). Next, push the local Parse Server to the newly created Heroku service using the following command:

$ git push heroku master

Paste the URL that the create command generated for you, 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 can test your new Heroku service still responds to GET requests. Remember to replace <myAppId> with you Application Id from the Parse Dashboard :

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

You should now be seeing 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//57eb6f36cd8bcce8141dc5ccca3072c0_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 just fully migrated your Parse app and database to the cloud and that was not a small task.

Implementing basic Push notifications

If you’re setting up Push notifications on iOS for the first time, please refer to the Push Notifications Tutorial for more information. You’ll need to save the exported push certificate in a safe place, as it’ll be needed in the next steps. When initializing the Parse Server you need to setup 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 should be the one you previously exported from the Push Notifications Tutorial . The bundleId should be the one you previously created, and production should be false if you’re using the Development certificate, or true if you’re using the Production certificate. Make sure to put the certificate inside the local Parse Server directory so it can be sent to the Heroku service:

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

Next, switch back to Xcode, open AppDelegate.swift and inside the application(_:didFinishLaunchingWithOptions:) method replace the following lines of code:

// Replace $0.server = "http://localhost:1337/parse"   // With This $0.server = "https://afternoon-harbor-27828.herokuapp.com/parse"

Next, add a private selector extension to your AppDelegate.swift file below the class definition:

// 1 private extension Selector {   // 2   /// Static selector to use for the **didReceiveRemoteNotification** selector argument   static let didReceiveRemoteNotification =  #selector(UIApplicationDelegate.application(_:didReceiveRemoteNotification:fetchCompletionHandler:)) }

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

  1. Using a private extension on the Selector type so its code is available only inside the AppDelegate.swift file
  2. Create a static Swift 2.2 Selector to be used inside your Selector definition below

Next, make your app register for remote Push notifications by adding the following lines in application(_: didFinishLaunchingWithOptions:) :

// 1 if application.applicationState != .Background {     // 2   let preBackgroundPush = !application.respondsToSelector(Selector("backgroundRefreshStatus"))   let oldPushHandlerOnly = !self.respondsToSelector(.didReceiveRemoteNotification)   var pushPayload = false   if let options = launchOptions {     pushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil   }   if (preBackgroundPush || oldPushHandlerOnly || pushPayload) {     PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)   } }   // 3 let types: UIUserNotificationType = [.Alert, .Badge, .Sound] let settings = UIUserNotificationSettings(forTypes: types, categories: nil) application.registerUserNotificationSettings(settings) application.registerForRemoteNotifications()

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

  1. Verify the app isn’t opening in Background mode
  2. Track an app open here if you launch with a push, unless “content_available” was used to trigger a background push. In that case, you need to skip tracking here to avoid double counting the app-open.
  3. Set the type of notifications your app wants to register for (Alert, Badge, Sound) and save them as the default notification settings.

Next, you need to store the device token and handle the UI for notifications. Add the following methods below application(_:didFinishLaunchingWithOptions:) :

// 1 func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {   let installation = PFInstallation.currentInstallation()   installation.setDeviceTokenFromData(deviceToken)   installation.saveInBackground() } // 2 func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {   if error.code == 3010 {     print("Push notifications are not supported in the iOS Simulator.")   } else {     print("application:didFailToRegisterForRemoteNotificationsWithError: %@", error)   } } // 3 func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {   PFPush.handlePush(userInfo)   if case(.Inactive) = application.applicationState {     PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)   } }

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

  1. This method is called when the app has successfully registered with the Apple Push Notification service (APNs). APNs push notifications with this provided deviceToken will be acted upon by the device. (All others will be ignored).
  2. This method is called when the APNs cannot successfully complete the device registration process due to an error. This method will be called with error information so your app can determine the cause of the registration failure.
  3. This method is called when your app receives a remote notification from the APNs. If the app is running, the app calls this method to process incoming remote notifications.

Build and run the app on an actual mobile device since Push Notifications are not supported in the iOS Simulator . To test, run this command in your terminal (don’t forget to replace the Application ID and Master Key from the Parse Dashboard , and the server url from Heroku ):

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://afternoon-harbor-27828.herokuapp.com/parse/push

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

Migrating Away From Parse

One more thing…

Only few days later, after having released Push notifications for the Parse Server, the great team at Parse also gave you the very useful Dashboard which can be used locally, as well as in the cloud. To install it locally, you first need to clone the Github repository on your machine:

$ git clone https://github.com/ParsePlatform/parse-dashboard.git $ cd parse-dashboard $ npm install

The dashboard will not work fully with the example Parse Server instance, only with versions 2.1.4 or newer. However, you can still get a glimpse of this powerful and useful tool which you can now use too, both in development and production. Next, you need to edit the parse-dashboard-config.json file in the Parse-Dashboard folder, and add your IDs, keys, URLs and names as shown below:

{   "apps": [     {       "serverURL": "https://api.parse.com/1",       "appId": "myAppId",       "masterKey": "myMasterKey",       "javascriptKey": "myJavascriptKey",       "restKey": "myRestKey",       "appName": "My Parse.Com App"     },     {       "serverURL": "http://localhost:1337/parse",       "appId": "myAppId",       "masterKey": "myMasterKey",       "appName": "My Parse Server App"     }   ] }

Next, run this command in the Parse Dashboard directory from the terminal:

$ npm run dashboard

Next, copy and paste http://localhost:4040 into your browser, and you’ll see your app in the Dashboard! For your apps on Parse.com, you can currently use the Data Browser, edit your Parse Config, use the API console, and view your Cloud Code and logs. For apps on the Parse Server, only the Data Browser and API console are available.

Migrating Away From Parse

Where To Go From Here?

You can download the finished projecthere. Remember to replace the AppID and ClientKey with your own keys.

As a follow up to this tutorial, you could explore more into the Parse Dashboard potential by using a full version of the Parse Server. You could also explore the extended capabilities of using a Push Adapter for other push providers that the default APN. Finally, you could look into and compare other Parse alternatives such as Firebase or CloudKit , beware though each of these alternatives lack some the features covered in this tutorial.

Parse.com is (soon) dead, long live the Parse Server!

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Migrating Away From Parse

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮