Couchbase Tutorial for iOS: Getting Started

In this Couchbase tutorial for iOS, you’ll learn how to use Couchbase and Sync Gateway to persist data across apps while making Ray’s Pizzeria App. By .

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

Adding Synchronization

In production, you’d use Couchbase Server and Sync Gateway; both installed on a server in some data center. The app would talk to Sync Gateway and handle the data synching between the server and mobile apps. However, you’re going to run Sync Gateway locally in walrus mode, which is an in-memory, development-only mode.

Installing Sync Gateway

Download Sync Gateway community edition and unzip the file. If you downloaded and unzipped the file to the Downloads folder, start it with this command in a Terminal window:

~/Downloads/couchbase-sync-gateway/bin/sync_gateway -dbname="pizza-db"

You should see Starting server on localhost:4984 ... in your Terminal window.

Go to http://localhost:4984 to see that it is up and running:

{couchdb:

Great, Sync Gateway is running! It’s time to replicate the database to the local server.

Synchronization

At the top of DataManager.swift, below the import section, add the following Notification.Name extension:

extension Notification.Name {
  public static let dbUpdated = Notification
    .Name("com.razeware.rayspizzeria.notification.name.dbUpdated")
}

Next, add the following to the property section:

private var replicator: Replicator?

Now, set up the replicator by adding the following to the end of init():

// 1
guard let syncURL = URL(string: "ws://localhost:4984/\(database.name)") else { return }

let syncEndpoint = URLEndpoint(url: syncURL)
let replicatorConfig = ReplicatorConfiguration(database: database, target: syncEndpoint)
replicatorConfig.continuous = true
replicator = Replicator(config: replicatorConfig)

// 2
replicator?.addChangeListener { (change) in
  let status = change.status
  if let error = status.error as NSError? {
    print("Error code :: \(error.code)")
  } else {
    guard status.progress.completed == status.progress.total else { return }

    NotificationCenter.default.post(name: .dbUpdated, object: nil)
  }
}

// 3
replicator?.start()

This code block does three things:

  • Notice the URL scheme is ws: instead of the usual http:. Couchbase Lite 2.0 uses WebSockets as its communication protocol.
  • replicatorConfig.continuous = true keeps the replicator active indefinitely waiting to replicate changed documents.
  1. Set up the replicator configuration and create the replicator.
  2. Listen for document changes and post a notification. You’ll add observers below to update the UI when these changes occur.
  3. Start the replicator.

In viewDidLoad() of MenuViewController.swift, CustomerViewController.swift, KitchenMenuViewController.swift and KitchenViewController.swift add:

NotificationCenter.default.addObserver(self, 
                                       selector: #selector(loadData(_:)), 
                                       name: .dbUpdated, 
                                       object: nil)

Build and run.

You’ll see GET /pizza-db/\_blipsync (as GUEST) in the Terminal window running sync_gateway.

You can see more information from Sync Gateway’s Admin panel (http://localhost:4985/_admin/db/pizza-db).

Admin view of pizza-db

Add a new customer. Refresh Sync Gateway’s Admin panel, and you’ll see a new file. Select the file to see the contents.

Admin view of customer

Simulate Multiple Users

To simulate multiple users, you can run the app on a second simulator. In Xcode, select a different simulator in scheme run destination.

Build and run.

You’ll see two simulators with one running RaysPizzeria. Tap the app icon in the other simulator to run the app.

Two simulators

To see changes in one simulator affect the other, make a few menu changes. In simulator one, select the Menu tab. In simulator two, select the Kitchen tab, tap the Menu bar button, select a pizza and change the price. Once you tap Save, the menu will update in simulator one.

Where to Go From Here?

You can download the completed version of the project using the Download Materials button at the top or bottom of this tutorial.

Couchbase is a great platform for app development, especially if your app is data-driven. You may have noticed that Couchbase Mobile does not require an additional networking layer/framework to download data or JSON parsing. Connecting your app to a Couchbase Server requires Sync Gateway and adding a Replicator in your code.

For more information about Couchbase Lite, check out their documentation. More detailed API documentation is here. You barely touched what’s available in the Query API. If you’re feeling adventours, expand the queries within this app.

We hope you enjoyed this Couchbase tutorial on Couchbase for iOS. If you have any questions or comments, please join the forum discussion below!

Contributors

Michael Gazdich

Tech Editor

Vladyslav Mytskaniuk

Illustrator

Essan Parto

Final Pass Editor

Richard Critz

Team Lead

Over 300 content creators. Join our team.