Navigation

ToDo (iOS App)

On this page

This tutorial demonstrates how to use MongoDB Stitch to integrate the following services for an iOS application:

  • Anonymous/Google/Facebook user authentication services
  • MongoDB service

This tutorial incorporates the services into a provided ToDo iOS application. The ToDo application maintains a single-user todo list. Users can log in using Google or Facebook credentials, add items to the list, check completed items and delete completed items.

The ToDo app uses the items collection in the todo database, which stores a document per each todo item.

Prerequisites

For this app, you need the following:

  • A MongoDB Atlas cluster using MongoDB version 3.4+. This tutorial uses an Atlas Free Tier cluster.
  • A developer account with either Google or Facebook (or both) for user authentication services.
  • iOS 9.0+
  • Xcode 8.2+ and an Xcode project.

Procedure

A. Create a MongoDB Stitch App

Estimated Time to Complete: ~8 minutes

1

Log into Atlas.

To use MongoDB Stitch, you must be logged into MongoDB Atlas. If you do not have an Atlas account, follow the instructions in the Atlas documentation to create an account.

2

Create an Atlas cluster.

If you do not already have an Atlas cluster for use with MongoDB Stitch, create a cluster.

Important

You must deploy the Atlas cluster with MongoDB version 3.4 or greater.

Atlas provides a Free Tier M0 replica set as well as paid M10+ clusters. Free Tier deployments have restrictions as compared to paid M10+ deployments but will work for the purposes of this tutorial. For complete documentation on these restrictions, see Atlas M0 (Free Tier), M2, and M5 Limitations.

3

Add a MongoDB Stitch application.

  1. In Atlas, click Stitch Apps in the left-hand navigation.
  2. Click the Create New Application. The name can only contain ASCII letters, numbers, underscores, and hyphens.
  3. Select your Atlas cluster.
  4. Click Create.

Upon creation of your app, you will be redirected to the MongoDB Stitch console. Your app is created with a MongoDB service named mongodb-atlas.

B. Define Rules

Estimated Time to Complete: ~6 minutes

MongoDB Stitch rules specify the read and write access for the fields in your collections.

1

Configure MongoDB.

Create a namespace for the todo.items collection:

  1. Click on mongodb-atlas under Atlas Clusters in the left navigation pane.
  2. Click on the Rules tab.
  3. In the Rules tab, click New to add a new namespace. Enter the following information:
    • For Database, enter todo.
    • For Collection, enter items.
  4. Click Create.

MongoDB Authorization

MongoDB Stitch rules do not override the read and write access (i.e. authorization) that may have been set up separately in MongoDB. That is, MongoDB Stitch rules determine whether the fields are readable or writable; not whether the client has authorization to read or write to a particular database or collection.

Similarly, MongoDB Stitch validation rules do not override document validation rules set up separately in MongoDB.

2

Review Read Rules for Top-Level Documents in todo.items.

To view the read rule, click on the Top-Level Document in the Field Rules view.

By default, the collection has the following read rule for the top-level document:

{
  "owner_id": "%%user.id"
}

With this rule, read and write operations can access all fields in a document if the document contains an owner_id field whose value equals the user ID (%%user.id) of the client issuing the read. If the owner_id field in the document does not equal the client user id, no field in the document is readable.

For more information on MongoDB read rules, see MongoDB Read Rules.

3

Modify Write Rules for Top-Level Documents in todo.items.

Modify the write rule at the top-level document to the following and click Save:

{
  "%or": [
    { "%%prevRoot.owner_id": "%%user.id" },
    { "%%prevRoot": { "%exists": false } }
  ]
}

The new rule specifies that the fields in a document are writable if either:

  • The write operation modifies a document where the value of owner_id previous to the write operation (%%prevRoot.owner_id) equaled the user ID (%%user.id) of the client issuing the write. An example of this kind of write operation is a client modifying a document that it previously inserted.
  • The write operation modifies a document where there was no document (%exists) previous to the write operation (%%prevRoot). An example of this kind of write operation is an insert of a new document.

For more information on MongoDB write rules, see MongoDB Write Rule.

4

Review Validation Rules for owner_id field in todo.items.

Click on the owner_id field to view its rules.

Modify the validation rule to the following and click Save:

"%%user.id"

The new rule requires that the value of owner_id equals the user ID (%%user.id) of the client issuing write. That is, MongoDB Stitch fails write operations that violate this rule.

For more information on validation rules, see MongoDB Validation Rules.

5

Review All Other Fields Enabled option for todo.items.

By default, Allow All Other Fields flag is enabled so that any unlisted fields are readable/writeable as long as the document meets the read/write rules. Alternatively, you can explicitly define all the fields for this collection and disable Allow All Other Fields to control the shape of the documents. For more information, see MongoDB Rules.

6

Review Filters for todo.items.

Click on the Filters.

By default, the collection has the following filter rule:

When Match Expression
{ "%%true": true } { "owner_id": "%%user.id" }

This filter indicates that when %%true equals true (i.e. always), apply the following filter { "owner_id": "%%user.id" } to the read and write operations. This filter is in addition to the query predicates for read and write operations.

For more information on filters, see MongoDB Filters.

C. Set Up Anonymous Auth

Estimated Time to Complete: 1 minute

To use Anonymous Authentication in the application:

1

Go to Authentication page.

Click Authentication in the left side navigation in the MongoDB Stitch console.

The Authentication page displays the Authentication Providers information.

2

Enable anonymous authentication.

  1. For Allow users to log in anonymously, click the Edit button.
  2. Switch the toggle to enabled.
  3. Close the dialog.

D. Set Up Facebook Authentication

Estimated Time to Complete: ~10 minutes

1

Set up an app in Facebook.

  1. Log in to your Facebook Developer account. If you do not have a Facebook developer account or even a Facebook account, see Facebook - Register and Configure an App.

  2. Add a new Facebook application.

  3. Once created, your application view opens to Product Setup. If not, go to your newly added app and click Add Product.

  4. In Product Setup, click Get Started for Facebook Login. The screen should display the Quickstart instructions.

  5. Choose iOS for your platform.

  6. In the Quick Start for iOS:

    1. You can skip the Download the Facebook SDK for iOS step and the Add Login Kit to your Xcode Project step as the ToDo iOS app project covers these steps.

    2. For the Add your Bundle Identifier step, enter the following and click Save:

      com.mongo.MongoDBSample
      
    3. Optional. You can enable/disable Single Sign On and continue to the next step.

    4. Note the following entry for your project file:

      FacebookAppID entry to copy into your project’s MongoDBSample/Resources/Info.plist file.

      <key>FacebookAppID</key>
      <string>1111111881399056</string>
      

      You will use this during the setup step of the ToDo iOS project in this tutorial.

    5. You can omit the remaining steps as they are already incorporated into the ToDo iOS project.

  7. Click Settings under Facebook Login in the left-hand navigation menu.

  8. Under Valid OAuth redirect URIs, add the following entry:

    https://stitch.mongodb.com/api/client/v2.0/auth/callback
    
  9. Save changes.

  10. Click Settings for your application (i.e. not the Settings under Facebook Login). Note the App ID and App Secret. You will use the information in the Authentication section of the MongoDB Stitch Admin Console.

2

Configure Stitch for Facebook Authentication.

  1. Click Authentication in the left side navigation in the MongoDB Stitch console.

    The Authentication page displays the Authentication Providers information.

  2. For Facebook, click the Edit button.

  3. In the Edit Provider dialog,

    • Switch the Facebook toggle to enabled.
    • Enter your new Facebook App ID in the Client ID field and Facebook App Secret in Client Secret field.
  4. Click Save.

E. Set Up Google Authentication

Estimated Time to Complete: ~10 minutes

Note

For Google authentication, you must create both iOS client credentials and web client credentials.

1

Set up a project in Google Cloud Platform.

  1. Log into your Google Cloud Platform (GCP) account. If you do not already have a GCP, create one by visiting https://cloud.google.com/.
  2. Open the GCP console.
  3. Select your preferred organization. If you have not yet created an organization in your GCP account, you must create one now.
  4. Create a new project for your MongoDB Stitch application. See Creating and Managing Projects for instructions.
2

Create the Web App client credentials.

From the GCP console, select the newly created project.

  1. Click the menu button, then APIs & services.

  2. Click Credentials.

  3. Create credentials, and select OAuth client ID.

    • For Application Type, select Web application.

    • For Name, enter the name you want to associate with this client ID.

    • For Authorized JavaScript origins, enter the following:

      https://stitch.mongodb.com
      
    • For Authorized redirect URIs, enter the following:

      https://stitch.mongodb.com/api/client/v2.0/auth/callback
      
  4. Click Create.

  5. Note the client ID and secret. You will use the information in the Authentication section of the MongoDB Stitch Console.

3

Download the GoogleService-Info.plist file.

  1. Go to https://console.firebase.google.com/

  2. Either import or add your newly created Google Project.

  3. Select Add Firebase to your iOS app.

  4. For your Bundle ID, enter the following:

    com.mongo.MongoDBSample
    
  5. Click Register App.

  6. Download the GoogleService-Info.plist. You will add the file to your iOS project in a later step.

  7. You can close the window or Skip to the console.

4

Configure Stitch Admin Console for Google Authentication

  1. Click Authentication in the left side navigation in the MongoDB Stitch console.

    The Authentication page displays the Authentication Providers information.

  2. For Google, click the Edit button.

  3. In the Edit Provider dialog,

    • Switch the Google toggle to enabled.
    • Enter your new Client ID and Client Secret from the Google Web App client credentials.
  4. Click Save.

F. Download the Application Source Code

Estimated Time to Complete: ~2 minutes

Download from the MongoDB Stitch github example repository and unzip it. The source code for the ToDo iOS application can be found in todo/ios directory.

G. Configure and Run the Application

1

Open the project in Xcode.

  1. Navigate to the downloaded example directory and navigate to the /todo/ios directory.
  2. Open the workspace file MongoDBSample.xcworkspace.
2

Update Xcode project with your MongoDB Stitch App ID.

From the MongoDBSample view:

  1. Open the MongoDBSample/Resources/Stitch-Info.plist file.

  2. Update the APP_ID with your MongoDB Stitch app id and save.

    In the MongoDB Stitch console, you can find your App ID in the Clients view.

3

Configure project authentication.

A. If using Facebook authentication:

  1. Delete the GoogleService-Info.plist highlighted in red. This is a placeholder configuration file for a Google authentication and must be removed when Google authentication is not used.
  2. Open the MongoDBSample/Resources/Info.plist file.
  3. Update the FacebookAppID with your facebook_app_id entry. The entry is listed in the step Configure Your info.plist in the Facebook iOS Login Quickstart.
  4. Click on the MongoDBSample project (not the folder) in the left hand navigation pane.
  5. Ensure the MongoDBSample target is selected by clicking on the MongoDBSample dropdown located on the left-hand side of General, then select MongoDBSample under Targets.
  6. Click on the Info tab and expand the URL Types.
  7. Click on the + to add a new URL.
  8. In the URL Schemes, enter the Facebook Login Protocol Scheme: fb<facebook_app_id>.

B. If using Google authentication:

  1. Delete the GoogleService-Info.plist highlighted in red.
  2. Drag the downloaded GoogleService-Info.plist into the project into the MongoDBSample/Resources folder.
  3. Leave the default options as is. Click Finish.
  4. Open the GoogleService-Info.plist and copy the REVERSED_CLIENT_ID.
  5. Click on the MongoDBSample project (not the folder) in the left hand navigation pane.
  6. Ensure the MongoDBSample target is selected by clicking on MongoDBSample dropdown located on the left-hand side of General, then select MongoDBSample under Targets.
  7. Click on the Info tab and expand the URL Types.
  8. Click on the + to add a new URL.
  9. In the URL schemes, paste in the value for the REVERSED_CLIENT_ID.
4

Review MongoDB Stitch connection logic in application source file.

The MongoDBSample/Classes/Controllers/TodoList/TodoListViewController.swift file contains logic that instantiates a stitchClient connection to your MongoDB Stitch app and instantiates a MongoClient instance that provides access to the MongoDB service named mongodb-atlas in your MongoDB Stitch app.

1
2
3
4
5
6
7
private let stitchClient = StitchClient(appId: Consts.AppId)
private var mongoClient: MongoDBClient

required init?(coder aDecoder: NSCoder) {
    mongoClient = MongoDBClient(stitchClient: stitchClient, serviceName: "mongodb-atlas")
    super.init(coder: aDecoder)
}
5

Run the todo app.

From the top menu bar, go to Product and select Clean. Then, select the iOS Simulator and run.