Back to Blogs

iOS: Pull to refresh with Couchbase Mobile

James Nocentini Published

Almost any app out there needs to display a list of information and when it comes to reloading data, users are expecting the pull to refresh feature to be available. Let’s explore how to do that with Sync Gateway and Couchbase Lite for iOS.

Data routing with "channels"

Sync Gateway uses channels to make it easy to share a database between a large number of users and control access to the database.

A replication from Sync Gateway specifies a set of channels to replicate. Documents that do not belong to any of the specified channels are ignored.

We'll use the following configuration for Sync Gateway:

On line 8, we enable the guest account and give it access to the public_recipes channel. Line 13 to line 17 is where we define the sync function: all documents of type recipe are routed to the public_recipes channel. In this example, we'll only use one type of document. But you could be working with many other types in your app.

Download Sync Gateway from here and start it:

$ ~/Downloads/sync_gateway/bin/sync_gateway config.js

Inserting documents

Now we have Sync Gateway running, we can save documents using the REST API. To create a new document, we must send a POST request to http://localhost:4984/cookbook/:

curl -X POST -H 'Content-Type: application/json' \ -d '{"type":"recipe", "title":"Lemon Chicken"}' \ http://localhost:4984/cookbook/

To make sure we can have new documents to fetch on every pull to refresh, use this bash script to save a new document with a 2 second interval.

Pull to Refresh

On the iOS side, all we have to do is to start a pull replication on the public_recipes channel when a pull to refresh gesture is detected. You can subscribe to notifications on the replication object and reload the table view accordingly when the replication has finished executing.

Download the source code of the PullToRefresh+CouchbaseLite example on github.

«   Back to blogs