This post looks at  how you can get started with Couchbase Lite in your iOS App. Couchbase Lite is an embedded JSON database that can work standalone, in a P2P network, or with a Sync Gateway as a remote endpoint. While we will be looking at the framework in the context of an iOS App in Swift, everything that’s discussed here applies equally to mobile apps developed in any other platform (Android, iOS (ObjC), Xamarin). Deviations will be specified as such. Stay tuned for related posts for the other platforms!

NOTE:  We will be discussing Couchbase Mobile v1.4 which is the current production release. There is a newer Developer Preview version 2.0 of Couchbase Mobile . We will dive into that in a future post.

Background

The Couchbase Mobile Stack comprises the Couchbase Server, Couchbase Sync Gateway and Couchbase Lite embedded Database. You can learn more about the server in the Getting started with Couchbase Server guide and the Sync Gateway in the Getting Started with Couchbase Sync Gateway guide.

I’ll assume you’re familiar with developing iOS Apps and basics of Swift. If you want to read up on NoSQL databases or Couchbase, you can find lots of resources on the Couchbase site.

Couchbase is open-source. Everything I’ll use here is free to try out.

Couchbase Lite

Couchbase Lite can be used in several deployment modes.

  • Option 1: It can be used as a standalone cross-platform embedded database on a device
  • Option 2: It can be used in conjunction with a remote Sync Gateway that would allow it to sync data across devices. This case can be extended to include the full Couchbase stack with the Couchbase Server. From the perspective of Couchbase Lite on the device, it should not really matter if there is a Couchbase Server or not since Couchbase Lite will interface with the remote Sync Gateway.
  • Option 3: It can be used in a P2P mode

We will focus on Option 1 here.

Native API

Couchbase Lite exposes a native API for iOS, Android and Windows that allows the Apps to easily interface with the Couchbase platform. As an App Developer, you do not have to worry about the internals of  the Couchbase Lite embedded database, but you can instead focus on building your awesome app . The native API allows you to interact with the Couchbase Lite framework just as you would interact with other platform frameworks/ subsystems. Again, we will be discussing Couchbase Mobile v1.4 in this blog post. You can get a full listing of the APIs on our Couchbase Developer site.

Integration

There are many options to integrate Couchbase Lite framework into your iOS App. It is probably the simplest to use Dependency Management Systems like Cocoapods or Carthage, but if you prefer, there is the option to manually include the framework into your app project . Check out our Couchbase Mobile Getting Started Guide for the various integration options.

Note that in case of a Swift app, after importing the framework, you will have to create a Bridging Header (if your app doesn’t already have one) and import the following files

 

Demo App

Please download the Demo Xcode project from this Github repo . We will use this app as an example in the rest of the blog.

 

This app uses Cocoapods to integrate the Couchbase Lite framework and is intended to familiarize you with the basics of using Couchbase Lite framework. Once downloaded, build and run the App. Play around with the app.You can use this app as a starting point and extend it to test the other APIs.

Couchbase Lite Demo

Couchbase Lite Standalone iOS App Demo

 

Basic Workflow

Creating a Local Database

Open the DBMainMenuViewController.swift file and locate the createDBWithName function.

This will create a database with specified name in the default path (/Library/Application Support). You can specify a different directory when you instantiate the CBLManager class.

  1. Create CBLDatabaseOptions object to associate with the database. For instance, you can set the encryption key to use with your database using the encryptionKey property. Explore the other options on CBLDatabaseOptions class.
  2. Database Names must to be lowercase. The sample app will automatically lowercase the names . If successful, a new local database will be created if it does not exist. If it exists, a handle to existing database will be returned.

Listing the Databases

This is very straightforward. Open the DBListTableViewController.swift file.  The allDatabaseNames property on CBLManager lists the databases that were created.

Adding a New Document to a Database

Open the DocListTableViewController.swift file and locate the createDocWithName function.

  1. As a result of this call, a Document is created with a unique Id
  2. You can specify a set of user properties as <key:value> pairs. There is an alternative in which you can use CBLDocumentModel object to specify your application data. The CBLDocumentModel is only available for the iOS platformWe will use <key:value> properties in our example

This creates new revision of the document with the specified user properties

Listing Documents in Database

Open the DocListTableViewController.swift file and locate the getAllDocumentForDatabase function

  1. Get handle to database with specified name
  2. Create a CBLQuery object. This Query is used to fetch all documents. You can create a regular query object or a “live” query object. The “live” query object is of type CBLLiveQuery that  automatically refreshes everytime the database changes in a way that affects the query results
  3. The query object  has a number of properties that can be tweaked in order to customize the results. Try modifying the properties and seeing the effect on results
  4. You will have to explicitly add an observer to the Live Query object be notified of changes to the database. We will discuss this more on section on “Observing Changes to Documents In Database”. Don’t forget to remove the observer and stop observing changes when you no longer need it!
  5.  Execute the query asynchronously. You can also do it synchronously if you prefer , but its probably recommended to do it async if the data sets are large.
  6. Once the query executes successfully, you get a CBLQueryEnumerator object. The query enumerator allows you to enumerate the results. It lends itself very well as a data source for the Table View that displays the results

Editing an Existing Document

 Open the DocListTableViewController.swift file and locate the updateDocWithName function.

  1. Get handle to document that needs to be edited. The CBLQueryEnumerator can be can be queried to fetch handle to the document at selected Index
  2. Update the user properties as <key:value> pairs. There is an alternative  in which you can use CBLDocumentModel object to specify your application data. This is only available on iOS. We will use <key:value> properties in our example.
  3. Updates to the document will require a revisionId to explicitly indicate the revision of the document that needs to be updated. This is specified using “_rev” key. This is required for conflict resolution. You can find more details here. This creates a new revision of the document with the specified user properties

Deleting an Existing Document

 Open the DocListTableViewController.swift file and locate the deleteDocAtIndex function.

  1. Get handle to document that needs to be edited. The CBLQueryEnumerator can be can be queried to fetch handle to the document at selected Index
  2. Delete the document. This deletes all revisions of document

Observing Changes to Documents in Database

Open the DocListTableViewController.swift file and locate the addLiveQueryObserverAndStartObserving function

  1. In order to be notified of changes to the database that affect the Query results, add an observer to the Live Query object . This is a case where the Swift/ Obj C versions differ from other mobile platforms. If you are developing on other platforms, you can call the addChangeListener API on the Live Query object. However,  in Couchbase Lite 1.4, this API is unsupported on the iOS platforms and we will instead leverage iOS’s Key-Value-Observer pattern  to be notified of changes.  Add a KVO observer to the Live Query object to start observing changes to the “rows” property on Live Query object
  2. Start observing changes

Whenever there is a change to the database that affects the “rows” property of the LiveQuery object, your app will be notified of changes. When you receive the notification of change, you can update your UI, which in this case would be reloading the tableview.

Deleting a Database

Open the DBListTableViewController.swift  file and locate the deleteDatabaseAtIndex function.

Deletion of a database is handled through a simple delete() call on the database.

Conclusion

As you can see, it is pretty straightforward to integrate a standalone version of Couchbase Lite into your new or existing iOS App. You can download the sample app discussed in this post from Github repo and try exploring the various interfaces.  If you have further questions, feel free to reach out to me at Twitter @rajagp or email me priya.rajagopal@couchbase.com.

The Couchbase Mobile Dev Forums is another great place to get your mobile related questions answered . Also, checkout out the Couchbase Developer Portal for more on Couchbase Mobile.

 

Posted by Priya Rajagopal, Developer Advocate, Couchbase

Priya Rajagopal is a Mobile Developer Advocate for Couchbase, living in Ann Arbor, MI. She has been professionally developing software for over 18 years and was most recently the Director of Mobile Development at a startup. Although her current interests lie in mobile development, she has previously worked on a range of technologies including IPTV, Social TV, targeted advertising, network management , RESTful architectures and platform security. As a TISPAN IPTV standards delegate, she was a key contributor to the IPTV architectural specifications. She has spent a decade in software R&D and is a co-inventor on almost 2 dozen US patents.

4 Comments

  1. […] of Couchbase Server, Sync Gateway and Couchbase Lite embedded NoSQL Database. In an earlier post, we discussed how Couchbase Lite can be used as a standalone embedded NoSQL database in iOS apps. […]

  2. […] mode. In this post, we will not go over the details of integrating with Couchbase Lite. The Getting Started With Couchbase Lite blog is a good place to get started on […]

  3. […] mode. In this post, we will not go over the details of integrating with Couchbase Lite. The Getting Started With Couchbase Lite blog is a good place to get started on […]

  4. […] mode. In this post, we will not go over the details of integrating with Couchbase Lite. The Getting Started With Couchbase Lite blog is a good place to get started on […]

Leave a reply