iOS: Real-time drawing app

2015-01-20

In this tutorial, we’ll look at how to build a very simple drawing app. We’ll use the powerful APIs provided by UIKit to handle touches and UI rendering. And with just a few more lines of code, you will add a real-time drawing feature that will be powered by Couchbase Lite and Sync Gateway.

Below is a short video of what you will be creating:

Getting Started

Start XCode and create a new project (Single View Application). Give it the name “DrawTogether” and select Swift in the Language dropdown menu.

1

You’ll use CocoaPods to add Couchbase Lite to your XCode project, run pod init from the command line in the app directory and add the following line to the Podfile that was generated:

pod 'couchbase-lite-ios', '~ 1.0.3.1'

Run pod install, close XCode and open DrawTogether.xcworkspace. We’ll use this file for the rest of the tutorial.

Create an Objective-C header file and import the CouchbaseLite framework:

2

Reference this file as an Objective-C Bridging Header in the Build Settings of the main target:

3

In AppDelegate.m, define your CBLDatabase and add a typealias for CBLDocument:

let kDatabase = CBLManager.sharedInstance().databaseNamed("drawtogether", error: nil)
typealias CBLDoc = CBLDocument

@UIApplication
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?

    ...

}

Quick on the Draw

First, we need to declare the model objects. Instructions for building Models with Couchbase Lite are explained here. Create a new Swift file named Polyline.swift subclassing CBLModel.

4

In Polyline.swift, add the following snippet:

Couchbase Lite stores documents as JSON. Properties declared with @NSManaged keep a one-to-one mapping relationship with the JSON document. This means we don’t need to do any JSON parsing. In init, you assign a type property to the document and initialize the points property. Following swift initialization rules, we must override the initDocument: because we will need it later on.

Your app will have one screen (ViewController). It will contain the drawing area and button to clear the drawing. In ViewController.swift, add the following properties:

Here’s a quick explanation of the variables used above:

  • drawImage is the image view storing the drawing.

  • polylines is the array of Polyline model objects. A polyline represents a continuous brush stroke.

  • currentPolyline stores the current polyline being drawn.

  • lastPoint is the last point corresponding to the last touch event.

In the viewDidLoad method setup drawImage:

Now for the drawing part, override the following methods in ViewController.swift:

Let’s break things down and explain what each method is doing:

  1. touchBegan:withEvent: is called on the first touch event detected and it sets the current polyline with the first point coordinates.

  2. touchesMoved:withEvent: is appending the following point to the current polyline, drawing the new point on drawImage and updating the lastPoint property.

  3. touchesEnded:withEvent: saves the currentPolyline to Couchbase Lite. Run the app, you should be able to see your drawings!

Before we jump to the multi-player feature, let’s add a Live Query property to be notified when new polylines are being indexed (received from other devices for example as we will see in Section 4). Add a liveQuery property of type CBLLiveQuery and initialize it in viewDidLoad:

Override observeValueForKeyPath:ofObject:change:context to handle the changes and add the drawPolylines method to draw the new polylines:

The Clear Button

In Interface Builder, add a button at the top and set the title to Clear. Add two AutoLayout constraints, one to center the button horizontally and one to set the top spacing to the containing view (click and drag from the button to the view to see the constraints popup appear).

5

Open Assistant Editor and create an IBAction by dragging from the button to ViewController.swift

6

In the body of the clearTap function, add the following code to delete all the documents stored in Couchbase Lite:

Real-time drawing

To make it more fun, we’ll use SyncGateway to replicate your drawing to other devices.

Create a new file called syncgateway-config.js in the app directory and paste the following configuration object. We are defining the drawtogether database and enabling the GUEST account.

Download the SyncGateway community edition for Mac OSX here. Unzip it and start it with the config file we created above:

$ ~/Downloads/couchbase-sync-gateway/bin syncgateway-config.js

Now let’s add the SyncGateway url to AppDelegate.swift. You can open Network Activity to get the internal IP of your computer.

7

That way, you will test the real-time feature between the simulator and a real device connecting to SyncGateway running on your machine.

In AppDelegate.swift, add this constant:

let kSyncGateway = "http://192.168.129.48:4984/drawtogether"

Notice the endpoint is the name of the database we defined in the config file.

Add the startReplications method to send and receive updates from Sync Gateway. Call it in applicationDidFinishLaunchingWithOptions:

Run your app and check the logs of your Sync Gateway server. All the documents in Couchbase Lite are being synced. To test that the replication is working, you can run the app on the simulator and your device at the same time.

Draw something, and see it instantly appearing on all other connected devices.

You can find the tutorial demo on github.

comments powered by Disqus