Skip to content
This repository has been archived by the owner on Mar 9, 2022. It is now read-only.

Example Snippets

snej edited this page Feb 8, 2012 · 11 revisions

CouchCocoa Example Snippets

Connecting To An Embedded Couchbase Mobile Database (iOS only)

This snippet requires that your app use the Couchbase Mobile framework, which embeds a CouchDB-compatible server inside your iOS app. In this case the startup is asynchronous; the CouchEmbeddedServer object will call a completion block when the server has started up, and you can then connect to it.

    CouchEmbeddedServer* server;
    server = [[CouchEmbeddedServer alloc] init];
    [server start: ^{  // ... this block runs later on when the server has started up:
        if (server.error) {
            [self failed: server.error]
            return;
        }
        self.database = [server databaseNamed: @"mydatabase"];
        // Create the database on the first run of the app.
        NSError* error;
        if (![self.database ensureCreated: &error]) {
            [self failed: error]
            return;
        }
    }];

Connecting To An Embedded TouchDB Database

If you use the TouchDB framework on iOS or Mac OS, make sure to check out the 'touchdb' branch of CouchCocoa. This branch has a CouchTouchDBServer class that makes it easy to start up TouchDB:

    CouchTouchDBServer* server = [CouchTouchDBServer sharedInstance];
    if (server.error) [self failed: server.error];
    self.database = [server databaseNamed: @"mydatabase"];
    NSError* error;
    if (![self.database ensureCreated: &error])
        [self failed: error];

Note that, unlike Couchbase Mobile, TouchDB starts up immediately so you don't have to worry about a callback block.

Connecting To A Remote Database

You can use CouchCocoa to talk to a CouchDB server on any accessible Internet host. In this example we assume we don't have admin access to the remote server, so the database must already exist. To verify the connection we do a GET operation on the database URL; we ignore the result, just check for an error.

    NSURL* serverURL = [NSURL URLWithString: @"http://example.com:8080"];
    CouchServer *server = [[CouchServer alloc] initWithURL: serverURL];
    CouchDatabase *database = [server databaseNamed: @"theirdatabase"];
    RESTOperation* op = [database GET];
    if (![op wait])
        [self failed: op.error]

Listing All The Documents In A Database

    CouchQuery* allDocs = database.allDocuments;
    for (CouchQueryRow* row in allDocs.rows) {
        CouchDocument* doc = row.document;
        NSString* message = [doc.properties objectForKey: @"message"];
        NSLog(@"Doc ID %@ has message: %@", row.documentID, message);
    }

Enumerating All Documents In A View (Query)

This example creates a CouchDB view (comparable to a stored SQL query) called "emailByName" that indexes all documents with a "name" property and associates the "email" property as the value. It then enumerates all the rows of the view/query (sorted by name) and writes the name and email.

    CouchDesignDocument* design = [database designDocumentWithName: @"mydesign"];
    [design defineViewNamed: @"emailByName" map: @"function(doc){if (doc.name) emit(doc.name,doc.email);};"];
    CouchQuery* query = [design queryViewNamed: @"emailByName"];
    for (CouchQueryRow* row in query.rows) {
        NSLog(@"%@'s email is <%@>", row.key, row.value);
    }

Note: The -defineViewNamed: method is smart enough to do nothing if the design document already contains a a view with the same name and function value, so it's OK to do the view creation right before you use the view; it won't cause extra database writes.

Updating A Document Asynchronously

Here we get a document's current properties (contents), make a mutable copy of them and update that, then store the changed properties back to the database. Instead of calling -wait on the operation, we add an onCompletion handler block that will run in the future when it finishes. That allows the code here to finish immediately without blocking (sic) the user interface.

    CouchRevision* latest = document.currentRevision;
    NSMutableDictionary* props = [[latest.properties mutableCopy] autorelease];
    int count = [[props objectForKey: @"count"] intValue];
    count++;
    [props setObject: [NSNumber numberWithInt: count] forKey: @"count"];

    RESTOperation* op = [latest putProperties: props];
    [op onCompletion: ^{
        if (op.isSuccessful)
            NSLog(@"Successfully updated document!");
        else
            NSLog(@"Failed to update document: %@", op.error);
    }];
Clone this wiki locally