Skip to content

Feed aggregator

Larry Page's Kitty Hawk company has a new flying car! - CNET

The Wisdom of Clouds - James Urquhart - Mon, 04/24/2017 - 20:12
The Google co-founder has backed a flying-car company called Kitty Hawk and its first prototype vehicle now has its very own video. Enjoy.
Categories: Blogs

Space station astronauts science their way into record book - CNET

The Wisdom of Clouds - James Urquhart - Mon, 04/24/2017 - 20:08
Talk about a busy work week. A recent ISS crew set a new record for devotion to science in space.
Categories: Blogs

Hate crowds, love cons? Here's how I cope - CNET

The Wisdom of Clouds - James Urquhart - Mon, 04/24/2017 - 20:00
What do you do when you want to go to pop-culture conventions but crowds make you want to run for the hills? Here are a few ideas.
Categories: Blogs

Galaxy S8 preorder numbers: How you like them apples? - CNET

The Wisdom of Clouds - James Urquhart - Mon, 04/24/2017 - 19:46
Preorder numbers for the Galaxy S8 and S8 Plus are the "best ever," the company says.
Categories: Blogs

Authorization and Authentication with RBAC (Part 2)

NorthScale Blog - Mon, 04/24/2017 - 19:30

Authorization and authentication are important to Couchbase. In March, I blogged about some of the new Role Based Access Control (RBAC) that we are showing in the Couchbase Server 5.0 Developer Builds. This month, I’d like to go into a little more detail now that the April Couchbase Server 5.0 Developer Build is available (make sure to click the “Developer” tab).

Authentication and authorization

In past version of Couchbase, buckets were secured by a password. In 5.0, bucket passwords for authorization are gone. You can no longer create a “bucket password” for authorization. Instead, you must create one (or more) users that have varying levels of authorization for that bucket. Notice that there is no “password” field anymore (not even in the “Advance bucket settings”:

Create a new Couchbase bucket - no password for authorization

So now, you no longer have to hand out a password that gives complete access to a bucket. You can fine-tune bucket authorization, and give out multiple sets of credentials with varying levels of access. This will help you tighten up security, and reduce your exposure.

Note: The administrator user still exists, and has permission to do everything. So I can still run N1QL queries (for instance) on that bucket while logged in as an administrator account. However, this is not the account you should be using from your clients.

Creating an authorized user

To create a new user, you must be logged in as an administrator (or as a user that has an Admin role). Go to the “Security” tab, and you’ll be able to see a list of users, and be able to add new ones.

Create a new user by clicking “ADD USER”. Enter the information for the user. You may want to create a user for a person (e.g. “Matt”), or you may want to create a user for a service (e.g. “MyAspNetApplication”). Make sure to enter a strong password, and then select the appropriate roles for the user you want to create.

For example, let’s create a user “Matt” that only has access to run SELECT queries on the bucket I just created. In “Roles”, I expand “Query Roles”, then “Query Select”, and check the box for “mynewbucket”, and then “Save” to finalize the user.

Create a new user with authorization to run a select query

Authorization in action

When I log out of the administrator account, and log back in as “Matt”, I can see that the authorization level I have is severely restricted. Only “Dashboard”, “Servers”, “Settings”, and “Query” are visible. If I go to “Query” I can execute SELECT 1;

Execute SELECT query logged in with only Query authorization

If I try something more complex, like SELECT COUNT(1) FROM mynewbucket, I’ll get an error message like:

[
  {
    "code": 13014,
    "msg": "User does not have credentials to access privilege cluster.bucket[mynewbucket].data.docs!read. Add role Data Reader[mynewbucket] to allow the query to run."
  }
]

So, it looks like I have the correct authentication to log in, and I have the correct authorization to execute a SELECT, but I don’t have the correct authorization to actually read the data. I’ll go back in as admin, and add Data Reader authorization.

User now has authorization for two roles

At this point, when I login with “Matt”, SELECT COUNT(1) FROM mynewbucket; will work. If you are following along, try SELECT * FROM mynewbucket;. You’ll get an error message that no index is available. But, if you try to CREATE INDEX you’ll need another permission to do that. You get the idea.

New N1QL functionality

There’s some new N1QL functionality to go along with the new authentication and authorization features.

GRANT and REVOKE ROLE

You can grant and revoke roles with N1QL commands. You need Admin access to do this.

Here’s a quick example of granting SELECT query authorization to a user named “Matt” on a bucket called “mynewbucket”:

GRANT ROLE query_select(mynewbucket) TO Matt;

And likewise, you can REVOKE a role doing something similar:

REVOKE ROLE query_select(mynewbucket) FROM Matt;

Creating users with REST

There is no way (currently) to create users with N1QL, but you can use the REST API to do this. Full documentation is coming later, but here’s how you can create a user with the REST API:

  • PUT to the /settings/rbac/users/builtin/<username> endpoint.

  • Use admin credentials for this endpoint (e.g. Administrator:password with basic auth)

  • The body should contain:

    • roles=<role1,role2,…​,roleN>

    • password=<password>

Below is an example. You can use cURL, Postman, Fiddler, or whatever your favorite tool is to make the request.

URL: PUT http://localhost:8091/settings/rbac/users/builtin/restman

Headers: Content-Type: application/x-www-form-urlencoded
Authorization: Basic QWRtaW5pc3RyYXRvcjpwYXNzd29yZA==

Body: roles=query_select[mynewbucket],query_update[mynewbucket]&password=password

The above assumes that you have an admin user/password of Administrator/password (hence the basic auth token of QWRtaW5pc3RyYXRvcjpwYXNzd29yZA==).

After executing that, you’ll see a new user named “restman” with the two specified permissions.

Create a new user with a REST command

Wait, there’s more!

The RBAC system is far too rich to cover in a single blog post, and full documentation is on its way. In the meantime, here are some details that might help you get started with the preview:

  • You may have noticed the all option in the screenshots above. You can give a user roles on a bucket-by-bucket basis, or you can give permission to all buckets (even buckets that haven’t been created yet).

  • I covered FTS permissions in the previous blog post, but there are permissions that cover just about everything: views, bucket administration, backup, monitoring, DCP, indexes, etc.

  • You can’t create buckets with a password anymore. The equivalent is to instead create a user with the name as the bucket, and give it authorization to a role called “Bucket Full Access”. This will be useful for upgrading and transitioning purposes.

We still want your feedback!

Stay tuned to the Couchbase Blog for information about what’s coming in the next developer build.

Interested in trying out some of these new features? Download Couchbase Server 5.0 April 2017 Developer Build today!

The 5.0 release is fast approaching, but we still want your feedback!

Bugs: If you find a bug (something that is broken or doesn’t work how you’d expect), please file an issue in our JIRA system at issues.couchbase.com or submit a question on the Couchbase Forums. Or, contact me with a description of the issue. I would be happy to help you or submit the bug for you (my Couchbase handlers let me take selfies on our cartoonishly big couch when I submit good bugs).

Feedback: Let me know what you think. Something you don’t like? Something you really like? Something missing? Now you can give feedback directly from within the Couchbase Web Console. Look for the feedback icon icon at the bottom right of the screen.

In some cases, it may be tricky to decide if your feedback is a bug or a suggestion. Use your best judgement, or again, feel free to contact me for help. I want to hear from you. The best way to contact me is either Twitter @mgroves or email me matthew.groves@couchbase.com.

The post Authorization and Authentication with RBAC (Part 2) appeared first on The Couchbase Blog.

Categories: Companies

Verizon launches Fios Gigabit internet for $70 a month - CNET

The Wisdom of Clouds - James Urquhart - Mon, 04/24/2017 - 19:04
The broadband provider promises ultra-fast uploads and downloads starting at $70 per month.
Categories: Blogs

Ford patents roof rack-mounted airbags for rollover protection - Roadshow

The Wisdom of Clouds - James Urquhart - Mon, 04/24/2017 - 19:00
Airbags traditionally work from the inside of the car, but this one is a bit different.
Categories: Blogs

Siri can now read WhatsApp messages to you - CNET

The Wisdom of Clouds - James Urquhart - Mon, 04/24/2017 - 18:52
"Hey Siri, read new WhatsApp messages."
Categories: Blogs

Sling TV cloud DVR hits Apple TV - CNET

The Wisdom of Clouds - James Urquhart - Mon, 04/24/2017 - 18:37
The internet TV company's cloud DVR is now available to Apple TV users for an extra $5 per month.
Categories: Blogs

Data Synchronization Across iOS Devices Using Couchbase Mobile

NorthScale Blog - Mon, 04/24/2017 - 18:30

This post looks at how you get started with data replication/synchronization across iOS devices using Couchbase Mobile. The Couchbase Mobile Stack comprises 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. This post will walk you through a sample iOS app in conjunction with a Sync Gateway that will demonstrate the core concepts of Push & Pull Replication, Authentication & Access Control, Channels and Sync Functions.

While we will be looking at data synchronization 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.

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 that has a lot of new and exciting features.

Couchbase Mobile

The Couchbase Mobile Stack comprises the Couchbase Server, Sync Gateway and Couchbase Lite embedded NoSQL Database. This post will discuss the basics of NoSQL data replication and synchronization using Couchbase Mobile. I’ll assume you’re familiar with developing iOS Apps, basics of Swift, some basics of NoSQL and have some understanding of Couchbase. If you want to read up more on Couchbase Mobile, you can find lots of resources at the end of this post.

Couchbase Sync Gateway

The Couchbase Sync Gateway is an Internet-facing synchronization mechanism that securely syncs data across devices as well as between devices and the cloud.

It exposes a web interface that provides

  • Data Synchronization across devices and the cloud
  • Access Control
  • Data Validation

You can use any HTTP client to further  explore the interface. Check out this post on using Postman for querying the interface.

There are three main¬†concepts related to¬†data replication or synchronization using the Sync Gateway –

Channel

A channel can be viewed as a combination of a tag and message queue. Every document can be assigned to one or more channels. Documents are assigned to channels which specify who can access the documents. Uses are granted access to one or more channels and can only read documents assigned to those channels. For details, check out the documentation on Channels.

 

Sync Function

The sync function is a JavaScript function that runs on the Sync Gateway. Every time a new document, revision or deletion is added to a database, the sync function is called. The sync function is responsible for

  • ¬†Validating the document,
  • Authorizing the change
  • Assigning document to channels and
  • Granting users‚Äô access to channels.

For details, check out documentation on Sync Function .

 

Replication

Replication a.k.a Synchronization is the process of synchronizing changes between local database and remote Sync Gateway. There are two kinds –

  • Push Replication is used to push changes from local to remote database
  • Pull Replication is used to pull changes from remote to local database

For details, check out documentation on replications.

 

Installation of Couchbase Sync Gateway

Follow the installation guide to install the Sync Gateway.

Launch your Sync Gateway with the following config file. The exact location of the config file will depend on the platform. Please refer to the install guide for the same.

Sync Gateway Config File

{
  "log": ["*"],
  "CORS": {
     "Origin":["*"]
  },
  "databases": {
    "demo": {
      "server": "walrus:",
      "bucket": "default",
      "users": { 
        "GUEST": { "disabled": true, "admin_channels": ["*"] } ,
        "joe": {"password":"password" ,"disabled": false, "admin_channels":["_public","_joe"]} ,
        "jane":{"password":"password" ,"disabled": false, "admin_channels":["_public","_jane"]}
      },
      "unsupported": {
        "user_views": {
          "enabled":true
        }
      },
    
  
  "sync": 
  `
      
      function (doc, oldDoc){
     

        // Check if doc is being deleted
        if (doc._deleted == undefined) {
          // Validate current version has relevant keys
          validateDocument(doc);
        }
        else {
          // Validate  old document has relevant keys
          validateDocument(oldDoc);
        }

        var docOwner = (doc._deleted == undefined) ? doc.owner : oldDoc.owner;
    

        var publicChannel = "_public";

        var privateChannel = "_"+docOwner;

        // Grant user read access to public channels and user's own channel
        access(docOwner,[publicChannel,privateChannel]);


        // Check if this was a doc update (as opposed to a doc create or delete)
        if (doc._deleted == undefined && oldDoc != null && oldDoc._deleted == undefined) {

            if (doc.tag != oldDoc.tag) {
                 throw({forbidden: "Cannot change tag of document"});
         
            }
        }


        // Check if new/updated document is tagged as "public" 
        var docTag =  (doc._deleted == undefined) ? doc.tag : oldDoc.tag;
    
        if (doc._deleted == undefined) {
          if (docTag == "public") {
           
            // All documents tagged public go into "public" channel which to open to all
            channel(publicChannel);
         
        }
        else {

            // Ensure that the owner of document is the user making the request
            requireUser(docOwner);

            // All non-public tagged docs go into a user user specific channel
            channel(privateChannel);

         }
       }
       else {
          channel(doc.channels);
       }


        function validateDocument (doc) {
           // Basic validation of document
          if (!doc.tag ) {
            // Every doc must include a tag
            throw({forbidden: "Invalid document type: Tag not provided" + doc.tag});
          }

           if (!doc.owner) {
            // Every doc must include a owner
            throw({forbidden: "Invalid document type: Owner not provided" + doc.owner});
          
          }
        }
      }
  

`
    }
  }
}

Here are some key points to note in the configuration file:-

  • Line 8: The ‚Äúwalrus:‚ÄĚ value for ‚Äúserver‚ÄĚ ¬†indicates that the Sync Gateway should persist data in-memory and is not backed by a Couchbase server.
  • Line 11: Guest user access is disabled
  • Line 12-13: There are two users, ‚ÄúJane‚ÄĚ and ‚ÄúJoe‚ÄĚ configured in the system. Both users have access to a ‚Äú_public‚ÄĚ channel and each has access to their own private channel.
  • Line 22-100: A¬†simple sync function that does the following
    1. Line 29-36 : Document validation to ensure that the document contains user defined ‚Äútag‚ÄĚ and ‚Äúowner‚ÄĚ properties
      1. The ‚Äútag‚ÄĚ property is used to specify if the document is publicly available to any user or if it is private to a user
      2. The ‚Äúowner‚ÄĚ property is used to specify if the document is publicly available to any user or if it is private to a user
    2. Line 46: Give user‚Äôs access to the ‚Äú_public‚ÄĚ and a private channel (identified using owner of document)
    3. Line 51-56 : If it‚Äôs a document update, verify that the ‚Äútag‚ÄĚ property is unchanged across revisions
    4. Line 66: Assign all documents with ‚Äúpublic‚ÄĚ tag to the ‚Äú_public‚ÄĚ channel
    5. Line 72: Assign all documents with a tag other than ‚Äúpublic‚ÄĚ to the private channel
      1. Line 75: For private channel documents, first verify that the document’s owner is the one making the request
Couchbase Lite

The Couchbase Lite is an embedded NoSQL database that runs on devices. Couchbase Lite can be used in several deployment modes. The Getting Started with Couchbase Lite  post discusses the standalone deployment mode. Couchbase Lite can be used in conjunction with a remote Sync Gateway that would allow it to sync data across devices. This post discusses the deployment mode using a Sync Gateway.

There are many options to integrate Couchbase Lite framework into your iOS App. Check out our Couchbase Mobile Getting Started Guide for the various integration options.

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.

Demo iOS App

Please download the Demo Xcode project from this¬†Github repo¬†and switch to “sync support” branch. We will use this app as an example in the rest of the blog. This app uses Cocoapods to integrate the Couchbase Lite framework.

git clone git@github.com:couchbaselabs/couchbase-lite-ios-standalone-sampleapp.git
git checkout syncsupport

 

Synchronization of Documents Across Users

  1. Build and Launch the App. You should be presented with a Login alert
  2. Enter user “jane” and password of “password” . This user was configured in the Sync Gateway config file
  3. Add first document by tapping on the “+” button on top right hand corner.
    1. Give a name to document and a one line description.
    2. Use tag “private”.
    3. Behind the scene, the Push Replicator pushes the document to the Sync Gateway and is¬†processed by the Sync Function. Based on the tag,¬†the Sync function assigns the document to the user’s private channel.
  4. Add second¬†document by tapping on the “+” button on top right hand corner.
    1. Give a name to document and a one line description
    2. Use tag “public”.
    3. Behind the scene, the Push Replicator pushes the document to the Sync Gateway and is processed by the Sync Function. Based on the public tag, the Sync function assigns the document to the public channel
  5. Now “log off” Jane¬†. You will be presented with the Login alert again
  6. Enter user “joe” and password of “password” . This user was also configured in the Sync Gateway config file
  7. The public document that was created by Jane will be listed.
    1. ¬†Behind the scenes,¬†the Pull Replicator pulls¬†all the documents from Joe’s private channel and the public channel. The¬†public document that was created by Jane is pulled. However, since Joe did not have access to Jane’s private channel, the private document created by Jane is not¬†pulled.

To verify the state of things on the Sync Gateway, you can use query the Admin REST interface using Postman or any HTTP client.

This is the CURL request to the Sync Gateway

curl -X GET \
 'http://localhost:4985/demo/_all_docs?access=false&channels=false&include_docs=true' \
 -H 'accept: application/json' \
 -H 'cache-control: no-cache' \
 -H 'content-type: application/json'

The Response from the Sync Gateway shows the two documents assigned to the public and Jane’s private channel respectively

{
  "rows": [
    {
      "key": "-6gCouN6jj0ScYgpMD7Qj1a",
      "id": "-6gCouN6jj0ScYgpMD7Qj1a",
      "value": {
        "rev": "1-dfa6d453a1515ee3dd64012ccaf53046",
        "channels": [
          "_jane"
        ]
      },
      "doc": {
        "_id": "-6gCouN6jj0ScYgpMD7Qj1a",
        "_rev": "1-dfa6d453a1515ee3dd64012ccaf53046",
        "name": "doc101",
        "overview": "This is a private doc from Jane",
        "owner": "jane",
        "tag": "private"
      }
    },
    {
      "key": "-A2wR44pAFCdu1Yufx14_1S",
      "id": "-A2wR44pAFCdu1Yufx14_1S",
      "value": {
        "rev": "1-1a8cd0ea3b7574cf6f7ba4a10152a466",
        "channels": [
          "_public"
        ]
      },
      "doc": {
        "_id": "-A2wR44pAFCdu1Yufx14_1S",
        "_rev": "1-1a8cd0ea3b7574cf6f7ba4a10152a466",
        "name": "doc102",
        "overview": "This is a public doc shared by Jane",
        "owner": "jane",
        "tag": "public"
      }
    }
  ],
  "total_rows": 2,
  "update_seq": 5
}

 

Exploring the Code

Now, lets examine relevant code snippets of the iOS Demo App –

Opening/ Creating a per-user Database 

Open DocListTableViewController.swift file and locate openDatabaseForUser function.

 do {
       // 1: Set Database Options
       let options = CBLDatabaseOptions()
       options.storageType  = kCBLSQLiteStorage
       options.create = true
            
       // 2: Create a DB for logged in user if it does not exist else return handle to existing one
       self.db  = try cbManager.openDatabaseNamed(user.lowercased(), with: options)
       self.showAlertWithTitle(NSLocalizedString("Success!", comment: ""), message: NSLocalizedString("Database \(user) was opened succesfully at path \(CBLManager.defaultDirectory())", comment: ""))
            
       // 3. Start replication with remote Sync Gateway
       startDatabaseReplicationForUser(user, password: password)
       return true
        }
        catch  {
            // handle error    
        }

  1. Specify the options to associate with the database. Explore the other options on CBLDatabaseOptions class.
  2. Create a database with name of the current user. This way, every user of the app will have their own local copy of the database. If a database exists with the name, a handle to existing database will be returned else a new one is created. Database Names must to be lowercase. If success, a new local database will be created if it does not exist. By default, database will be created in the default path (/Library/Application Support). You can specify a different directory when you instantiate the CBLManager class.
  3. Start Database Replication Process for given user credentials. We will discuss Replication code in detail in the following sections.
Fetching Documents

Open the DocListTableViewController.swift file and locate getAllDocumentForUserDatabase  function.

// 1. Create Query to fetch all documents. You can set a number of properties on the query object
liveQuery = self.db?.createAllDocumentsQuery().asLive()
            
guard let liveQuery = liveQuery else {
       return
}
            
// 2: You can optionally set a number of properties on the query object.
// Explore other properties on the query object
liveQuery.limit = UInt(UINT32_MAX) // All documents
            
//   query.postFilter =
            
//3. Start observing for changes to the database
self.addLiveQueryObserverAndStartObserving()
            
            
// 4: Run the query to fetch documents asynchronously
liveQuery.runAsync({ (enumerator, error) in
        switch error {
            case nil:
            // 5: The "enumerator" is of type CBLQueryEnumerator and is an enumerator for the results
            self.docsEnumerator = enumerator
                    
                    
            default:
            self.showAlertWithTitle(NSLocalizedString("Data Fetch Error!", comment: ""), message: error.localizedDescription)
                }
            })            
        }
        catch  {
            // handle error            
        }

  1. Get handle to database with specified name
  2. Create a query object. This Query is used to fetch all documents. The Sync Function on the Sync Gateway will ensure that documents are pulled ¬†from only the channels ¬†that are accessible to the user.¬†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. The query 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
  3. 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 Local & Remote Synchronized¬†Changes to Documents‚ÄĚ. Don‚Äôt forget to remove the observer and stop observing changes when you no longer need it!
  4. 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.

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

Observing Local & Remote Synchronized Changes to Documents 

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

Changes to the database could be as a result of the user’s actions on the local¬†device or could be a result of changes synchronized from other devices.

 // 1. iOS Specific. Add observer to the live Query object
    liveQuery.addObserver(self, forKeyPath: "rows", options: NSKeyValueObservingOptions.new, context: nil)
        
 // 2. Start observing changes
    liveQuery.start()

  1. In order to be notified of changes to the database that affect the Query results, add an observer to the Live Query object . 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 This is handled through appropriate Event Handler APIs on other platforms such as the addChangeListener function on¬†Android/Java.
  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.

if keyPath == "rows" {
    self.docsEnumerator = self.liveQuery?.rows
    tableView.reloadData()
}

 

Authentication of Replication Requests

Open DocListTableViewController.swift file and locate startDatabaseReplicationForUser function.

All Replication requests must be authenticated. In this app, we use HTTP Basic Authentication.

let auth = CBLAuthenticator.basicAuthenticator(withName: user, password: password)

There are several Authenticator types namely ‚Äď Basic, Facebook, OAuth1, Persona, SSL/TLS Cert.

Pull Replication

Open DocListTableViewController.swift file and locate startPullReplicationWithAuthenticator function.

// 1: Create a Pull replication to start pulling from remote source
let pullRepl = db?.createPullReplication(URL(string: kDbName, relativeTo: URL.init(string: kRemoteSyncUrl))!)
        
// 2. Set Authenticator for pull replication
pullRepl?.authenticator = auth
        
// Continuously look for changes
pullRepl?.continuous = true
        
// Optionally, Set channels from which to pull
// pullRepl?.channels = [...]
        
 // 4. Start the pull replicator
 pullRepl?.start()

  1. Create a Pull Replicator to pull changes from remote Sync Gateway. The kRemoteSyncUrl is the URL of the remote database endpoint on the Sync Gateway.
  2. Associate Authenticator with the Pull Replication. Optionally one can set the channels from which documents should be pulled
  3. Setting replication to ‚Äúcontinuous‚ÄĚ will allow change updates to be pulled indefinitely unless explicitly stopped or database is closed.
  4. Start the Pull Replication
Push Replication

Open DocListTableViewController.swift file and locate startPushReplicationWithAuthenticator function.

// 1: Create a push replication to start pushing to remote source
let pushRepl = db?.createPushReplication(URL(string: kDbName, relativeTo: URL.init(string:kRemoteSyncUrl))!)
        
// 2. Set Authenticator for push replication
pushRepl?.authenticator = auth
        
// Continuously push  changes
pushRepl?.continuous = true
        
        
// 3. Start the push replicator
pushRepl?.start()

  1. Create a Push Replicator to push changes to remote Sync Gateway. The kRemoteSyncUrl is the URL of the remote database endpoint on the Sync Gateway.
  2. Associate Authenticator with the Push Replication.
  3. Setting replication to ‚Äúcontinuous‚ÄĚ will allow change updates to be pushed indefinitely unless explicitly stopped or database is closed.
  4. Start the Push Replication
Monitoring the Status of the Replication

Open the DBListTableViewController.swift file and locate addRemoteDatabaseChangesObserverAndStartObserving function.

// 1. iOS Specific. Add observer to the NOtification Center to observe replicator changes
NotificationCenter.default.addObserver(forName: NSNotification.Name.cblReplicationChange, object: db, queue: nil) {
            [unowned self] (notification) in
          
  // Handle changes to the replicator status - Such as displaying progress
  // indicator when status is .running 
}

 

You can monitor the status of the replication by adding an observer to the iOS Notification Center to be notified of cblReplicationChange notifications . You could use the notification handler for instance, to display appropriate progress indicators to user.  This is handled through appropriate Event Handler APIs on other platforms such as the addChangeListener function on Android/Java.

What Next ?

We would love to hear from you. So if you have questions or feedback, feel free to reach out to me at Twitter @rajagp or email me priya.rajagopal@couchbase.com. If you would like to enhance the demo app, please submit a pull request to the Github Repo.

The Couchbase Mobile Dev Forums is another great place to get your mobile related questions answered .Check out the development portal for details on the Sync Gateway and Couchbase Lite . Everything that was discussed here is on the Context of Couchbase Mobile 1.4. There are a lot of new and exciting changes coming up on Couchbase Mobile 2.0. Be sure to check out the  Developer Preview version 2.0 of Couchbase Mobile.

The post Data Synchronization Across iOS Devices Using Couchbase Mobile appeared first on The Couchbase Blog.

Categories: Companies

What would you do for an NES Classic? (The 3:59, Ep. 215) - CNET

The Wisdom of Clouds - James Urquhart - Mon, 04/24/2017 - 18:24
We also offer up a wish list for SNES Classic features and talk about the March for Science.
Categories: Blogs

Samsung offers brilliant one-emoji putdown of Twitter troll - CNET

The Wisdom of Clouds - James Urquhart - Mon, 04/24/2017 - 18:13
Commentary: The Galaxy S8 maker asks tweeters about their first picture taken with the new phone. One wag thinks he's being clever.
Categories: Blogs

Is a base-trim Honda Civic Type R in the works? - Roadshow

The Wisdom of Clouds - James Urquhart - Mon, 04/24/2017 - 18:00
If so, it could make Honda's hottest hatch even cheaper.
Categories: Blogs

Yi, Google partner for next-gen Halo VR Jump camera rig - CNET

The Wisdom of Clouds - James Urquhart - Mon, 04/24/2017 - 17:20
The 17-camera setup can record 8K-resolution stereoscopic VR video stitched together with Google's Jump Assembler.
Categories: Blogs

Goat fugitives go for ride-along in police car - CNET

The Wisdom of Clouds - James Urquhart - Mon, 04/24/2017 - 17:01
A police officer turns to Facebook to reunite a charismatic pair of escaped goats with their family.
Categories: Blogs

Tesla hopes to double Supercharger network in 2017 - Roadshow

The Wisdom of Clouds - James Urquhart - Mon, 04/24/2017 - 17:00
In the US alone, Tesla wants to increase its Supercharger network by 150 percent.
Categories: Blogs

The next Audi A8 will be capable of Level 3 autonomous driving - Roadshow

The Wisdom of Clouds - James Urquhart - Mon, 04/24/2017 - 17:00
The new A8 should make its debut some time in 2017.
Categories: Blogs

Trump calls space station to congratulate record-setting astronaut - CNET

The Wisdom of Clouds - James Urquhart - Mon, 04/24/2017 - 16:35
Commander Peggy Whitson broke the record for longest cumulative stay in space by a US astronaut today, logging her 534th day.
Categories: Blogs

AR is like your phone: Soon you'll feel naked without it - CNET

The Wisdom of Clouds - James Urquhart - Mon, 04/24/2017 - 16:22
Commentary: VR is here, but the true reality revolution is augmented.
Categories: Blogs

Mars rover's landing hardware still visible 13 years later - CNET

The Wisdom of Clouds - James Urquhart - Mon, 04/24/2017 - 16:08
Revisit the very beginning of the Mars Opportunity rover's epic mission with a new NASA view of its landing platform and parachute.
Categories: Blogs