{"id":10274,"date":"2023-08-28T06:56:25","date_gmt":"2023-08-28T13:56:25","guid":{"rendered":"https:\/\/www.couchbase.com\/developers\/tutorials\/quickstart-ios-uikit-sync\/"},"modified":"2023-08-28T06:56:25","modified_gmt":"2023-08-28T13:56:25","slug":"quickstart-ios-uikit-sync","status":"publish","type":"tutorials","link":"https:\/\/www.couchbase.com\/ja\/developers\/tutorials\/quickstart-ios-uikit-sync\/","title":{"rendered":"iOS\u3001Swift\u3001UIKit\u306b\u3088\u308bCouchbase Lite Data Sync\u306e\u30af\u30a4\u30c3\u30af\u30b9\u30bf\u30fc\u30c8"},"content":{"rendered":"\n<h3 id=\"h-introduction\" class=\"wp-block-heading\">Introduction<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Couchbase Sync Gateway is a key component of the Couchbase Mobile stack. It is an Internet-facing synchronization mechanism that securely syncs data across devices as well as between devices and the cloud. Couchbase Mobile uses a websocket based <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/couchbase-lite\/current\/swift\/replication.html#replication-protocol\">replication protocol<\/a>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The core functions of the Sync Gateway include<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Data Synchronization across devices and the cloud<\/li>\n\n\n<li>Authorization &amp; Access Control<\/li>\n\n\n<li>Data Validation<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">This tutorial will demonstrate how to &#8211;<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Installing Couchbase Server using Docker and Docker Compose<\/li>\n\n\n<li>Automation of Couchbase Server cluster setup and importing of data<\/li>\n\n\n<li>Installing Sync Gateway using Docker and Docker Compose<\/li>\n\n\n<li>Setup of a Sync Gateway configuration file<\/li>\n\n\n<li>Configure your Couchbase Lite clients for replication with the Sync Gateway<\/li>\n\n\n<li>Use &#8220;Live Queries&#8221; or Query events within your Couchbase Lite clients to be asynchronously notified of changes<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">We will be using a Swift App as an example of a Couchbase Lite enabled client.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">You can learn more about the Sync\nGateway here in the <a target=\"_blank\" rel=\"noopener \nnoreferrer\" href=\"https:\/\/docs.%0Acouchbase.com\/sync-gateway\/current%0A\/index.html\">Sync Gateway Documentation<\/a>.<\/p>\n<\/blockquote>\n\n\n\n<h3 id=\"h-prerequisites\" class=\"wp-block-heading\">Prerequisites<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This tutorial assumes familiarity with building swift apps with Xcode and with Couchbase Lite.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>\n<p>If you are unfamiliar with the basics of Couchbase Lite, it is recommended that you walk through the following tutorials<\/p>\n<ul>\n<li>Fundamentals of using Couchbase Lite as a standalone database &#8211; see <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/developer.couchbase.com\/tutorial-quickstart-ios-uikit-basic\">Quickstart in Couchbase Lite with iOS, Swift, and UIKit<\/a><\/li>\n<li>Query Basics with a prebuilt version of Couchbase Lite database &#8211; see <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/developer.couchbase.com\/tutorial-quickstart-ios-uikit-query\">Quickstart in Couchbase Lite Query with iOS, Swift, and UIKit<\/a><\/li>\n<\/ul>\n<\/li>\n\n\n<li>\n<p>iOS (Xcode 14\/15) &#8211; Download\nlatest version from the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/itunes.apple.com\/us\/app\/xcode\/id497799835?mt=12\">Mac App Store<\/a> or via <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/github.com\/RobotsAndPencils\/XcodesApp\">Xcodes<\/a><\/p>\n<\/li>\n\n<\/ul>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><strong>Note<\/strong>: If you are using an older version of Xcode, which you need to retain for other development needs, make a copy of your existing version of Xcode and install the latest Xcode version.  That way you can have multiple versions of Xcode on your Mac.  More information can be found in <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/developer.apple.com\/library\/archive\/technotes\/tn2339\/_index.html#\/\/apple_ref\/doc\/uid\/DTS40014588-CH1-I_HAVE_MULTIPLE_VERSIONS_OF_XCODE_INSTALLED_ON_MY_MACHINE__WHAT_VERSION_OF_XCODE_DO_THE_COMMAND_LINE_TOOLS_CURRENTLY_USE_\">Apple&#8217;s Developer Documentation<\/a>. The open source <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/github.com\/RobotsAndPencils\/XcodesApp%20\">Xcodes<\/a> project makes managing multiple installations of Xcode easier.<\/p>\n<\/blockquote>\n\n\n\n<ul class=\"wp-block-list\">\n<li>\n<p>curl HTTP client<\/p>\n<ul>\n<li>You could use any HTTP client of your choice. But we will use <em>curl<\/em> in our tutorial. Package manager users can use <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/brew.sh\/\">homebrew<\/a>.<\/li>\n<\/ul>\n<\/li>\n\n\n<li>\n<p>Docker<\/p>\n<ul>\n<li>We will be using Docker to run images of both Couchbase Server and the Sync Gateway \u2014 to download Docker, or for more information, see: <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.docker.com\/get-docker\/\">Get Docker<\/a>.<\/li>\n<\/ul>\n<\/li>\n\n<\/ul>\n\n\n\n<h3 id=\"h-system-overview\" class=\"wp-block-heading\">System Overview<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">We will be working with a simple &#8220;User Profile&#8221; app which we introduced in the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/developer.couchbase.com\/tutorial-quickstart-ios-uikit-basic\">Quickstart in Couchbase Lite with iOS, Swift, and UIKit<\/a> tutorial and extended in the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/developer.couchbase.com\/tutorial-quickstart-ios-uikit-query\">Quickstart in Couchbase Lite Query with iOS, Swift, and UIKit<\/a> tutorial.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this tutorial, we will be extending that app to support data sync.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The app does the following<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>\n<p>Allows users to log in and create or update his\/her user profile information. The user profile view is <strong><em>automatically updated<\/em><\/strong> everytime the profile information changes in the underlying database.<\/p>\n<\/li>\n\n\n<li>\n<p>The user profile information is synced with a remote Sync Gateway which then syncs it to other devices (subject to access control and routing configurations specified in the <code>sync function<\/code>).<\/p>\n<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><img decoding=\"async\" src=\".\/userprofile_app_overview.gif\" alt=\"App with Sync\"><\/p>\n\n\n\n<h3 id=\"h-app-installation\" class=\"wp-block-heading\">App Installation<\/h3>\n\n\n\n<h4 id=\"h-fetching-app-source-code\" class=\"wp-block-heading\">Fetching App Source Code<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">To clone the project from GitHub, type the following command in your terminal:<\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>git clone https:\/\/github.com\/couchbase-examples\/ios-swift-cblite-userprofile-sync\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-installing-couchbase-lite-xcframework\" class=\"wp-block-heading\">Installing Couchbase Lite XCFramework<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Next, we will download the Couchbase Lite 3.0 XCFramework.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The Couchbase Lite iOS XCFramework is distributed via SPM, CocoaPods, Carthage, or you can download the pre-built framework.  See the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/couchbase-lite\/3.0\/swift\/gs-install.html\"> Getting Started &#8211; Install<\/a> documentation for more information.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In our example, we will be downloading the pre-built version of the XCFramework, using a script. To do this, type the following in a command terminal replacing the path with the path on your computer:<\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>  cd \/path\/to\/cloned\/repo\/ios-swift-cblite-userprofile-sync\/src\n\n  sh install_tutorial.sh\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Now, let&#8217;s verify the installation.<\/p>\n\n\n\n<h4 id=\"h-try-it-out\" class=\"wp-block-heading\">Try it Out<\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Open the <code>UserProfileSyncDemo.xcodeproj<\/code>. The project would be located at <code>\/path\/to\/cloned\/repo\/ios-swift-cblite-userprofile-sync\/src<\/code><\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>open UserProfileSyncDemo.xcodeproj\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>\n<p>Build and run the project using <strong>two different simulators<\/strong> using Xcode<\/p>\n<\/li>\n\n\n<li>\n<p>Verify that you see the login screen on both the simulators<\/p>\n<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><img decoding=\"async\" src=\".\/user_profile_login_2.png\" alt=\"User Profile Login Screen Image\"><\/p>\n\n\n\n<h3 id=\"h-data-model\" class=\"wp-block-heading\">Data Model<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">If you have followed along the tutorial <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/developer.couchbase.%0Acom\/tutorial-quickstart-ios-uikit-query\">Quickstart in Couchbase Lite Query with iOS, Swift, and UIKit<\/a>, you can skip this section and proceed to the <a href=\"#backend-installation\">Backend Installation<\/a> section as we have not made any changes to the Data model for this tutorial.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Couchbase Lite is a JSON Document Store. A Document is a logical collection of named fields and values.The values are any valid JSON types. In addition to the standard JSON types, Couchbase Lite supports some special types like <code>Date<\/code> and <code>Blob<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">While it is not required or enforced, it is a recommended practice to include a <strong><em>&#8220;type&#8221;<\/em><\/strong> property that can serve as a namespace for related.<\/p>\n\n\n\n<h4 id=\"h-the-user-profile-document\" class=\"wp-block-heading\">The &#8220;User Profile&#8221; Document<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The app deals with a single Document with a <strong><em>&#8220;type&#8221;<\/em><\/strong> property of <strong><em>&#8220;user&#8221;<\/em><\/strong>.  The document ID is of the form <strong><em>&#8220;user::&lt;email&gt;&#8221;<\/em><\/strong>.\nAn example of a document would be:<\/p>\n\n\n\n<pre class=\"wp-block-code language-json\"><code>{\n    &quot;type&quot;:&quot;user&quot;,\n    &quot;name&quot;:&quot;Jane Doe&quot;,\n    &quot;email&quot;:&quot;jame.doe@earth.org&quot;,\n    &quot;address&quot;:&quot;101 Main Street&quot;,\n    &quot;image&quot;:CBLBlob (image\/jpg),\n    &quot;university&quot;:&quot;Rensselaer Polytechnic&quot;\n}\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-userrecord\" class=\"wp-block-heading\">UserRecord<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The <strong><em>&#8220;user&#8221;<\/em><\/strong> Document is encoded to a native struct named <strong><em>UserRecord<\/em><\/strong>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-swift\"><code>let kUserRecordDocumentType = &quot;user&quot;\ntypealias ExtendedData = [[String:Any]]\nstruct UserRecord : CustomStringConvertible{\n  let type = kUserRecordDocumentType\n  var name:String?\n  var email:String?\n  var address:String?\n  var imageData:Data?\n  var university:String?\n  var extended:ExtendedData? \/\/ future\n\n  var description: String {\n      return &quot;name = (String(describing: name)), email = (String(describing: email)), address = (String(describing: address)), imageData = (imageData)&quot;\n  }\n}\n<\/code><\/pre>\n\n\n\n<h3 id=\"h-the-university-document\" class=\"wp-block-heading\">The &#8220;University&#8221; Document<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The app comes bundled with a collection of Documents of type <strong><em>&#8220;university&#8221;<\/em><\/strong>. Each Document represents a university.<\/p>\n\n\n\n<pre class=\"wp-block-code language-json\"><code>{\n    &quot;type&quot;:&quot;university&quot;,&quot;web_pages&quot;: [\n      &quot;http:\/\/www.rpi.edu\/&quot;\n    ],\n    &quot;name&quot;: &quot;Rensselaer Polytechnic Institute&quot;,\n    &quot;alpha_two_code&quot;: &quot;US&quot;,\n    &quot;state-province&quot;: null,\n    &quot;domains&quot;: [\n      &quot;rpi.edu&quot;\n    ],\n    &quot;country&quot;: &quot;United States&quot;\n}\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-universityrecord\" class=\"wp-block-heading\">UniversityRecord<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The <strong><em>&#8220;university&#8221;<\/em><\/strong> Document is encoded to a native struct named <strong><em>UniversityRecord<\/em><\/strong>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-swift\"><code>typealias Universities = [UniversityRecord]\n\/\/ Native object\nstruct UniversityRecord : CustomStringConvertible{\n  var alphaTwoCode:String?\n  var country:String?\n  var domains:[String]?\n  var name:String?\n  var webPages:[String]?\n  \n  var description: String {\n      return &quot;name = (String(describing: name)), country = (String(describing: country)), domains = (String(describing: domains)), webPages = (webPages), alphaTwoCode = (String(describing: alphaTwoCode)) &quot;\n  }\n}\n<\/code><\/pre>\n\n\n\n<h3 id=\"h-backend-installation\" class=\"wp-block-heading\">Backend Installation<\/h3>\n\n\n\n<h4 id=\"h-prerequisites\" class=\"wp-block-heading\">Prerequisites<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">In this step of the tutorial, we\nwill be using docker and docker compose and should have both of these installed  before continuing.  <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/www.docker.com\/products\/docker-desktop\/\">Docker Desktop<\/a> provides these tools and UI for Mac, Windows, and Linux.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You might also want a text editor\noutside XCode to review the docker\nand docker compose config files.  Any text editor will work, but for many developers Visual Studio Code is a good solution as it provides extensions for Docker config file formatting and YAML support, which is a file format Docker Compose uses.  You can download Visual Studio code <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/code.visualstudio.com\/download\">here<\/a>.  If you are using Visual Studio code make sure you install the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/code.visualstudio.com\/docs\/containers\/overview\">Docker extension<\/a>.  The <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/github.com\/redhat-developer\/vscode-yaml\">YAML Language Support<\/a> is another great extension that can be a major quality of life improvement if you use YAML files a lot.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><strong>NOTE<\/strong>: This part of the\ntutorial is longer than normal as there are several configuration files to review.  For developers looking to try\nout the containers without reviewing the configuration files, you can skip to the [Try It Out &#8211; Docker Compose]\n(#try-docker-compose) section.<\/p>\n<\/blockquote>\n\n\n\n<h4 id=\"h-review-setup-of-docker-containers\" class=\"wp-block-heading\">Review Setup of Docker Containers<\/h4>\n\n\n\n<h5 id=\"h-couchbase-server-dockerfile\" class=\"wp-block-heading\">Couchbase Server &#8211; Dockerfile<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Docker and Docker Compose will be used to create a Couchbase Server container that has a one node cluster setup with a bucket, a user for sync gateway to perform replication between the sync gateway server and server, and indexes for the bucket.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This is accomplished by creating a custom Dockerfile that defines the Couchbase Server base image along with a shell scripts to perform the automation of the Couchbase Server cluster setup and importing of sample data.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Open the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/github.com\/couchbase-examples\/ios-swift-cblite-userprofile-sync\/blob\/main\/src\/couchbase-server\/Dockerfile\">Dockerfile<\/a> found in the couchbase-server folder in the root of the repo in a text editor of your choice.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-docker\"><code>FROM couchbase\/server:latest AS stage_base\nCOPY init-cbserver.sh \/opt\/couchbase\/init\/\n<\/code><\/pre>\n\n\n\n<ol class=\"wp-block-list\">\n<li>The first line tells docker which docker container should be used as the <code>base<\/code> image for this container.  We are using the <code>couchbase:latest<\/code> image.  As of Couchbase Server 7.1 &#8211; ARM64 and X86 images are provided.<\/li>\n\n\n<li>Next it copies the init-cbserver.sh shell script into the containers \/opt\/couchbase\/init folder<\/li>\n\n<\/ol>\n\n\n\n<h5 id=\"h-automation-using-shell-script\" class=\"wp-block-heading\">Automation using Shell Script<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Next open the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/github.com\/couchbase-examples\/ios-swift-cblite-userprofile-sync\/blob\/main\/src\/couchbase-server\/init-cbserver.sh\">init-cbserver.sh<\/a> file found in the same folder as the Dockerfile.  This shell script is well documented with comments before each line, however we will still go through the script from a high level.<\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>#!\/bin\/bash\n# used to start couchbase server - can&#039;t get around this as docker compose\n# only allows you to start one command - so we have to start couchbase like the Dockerfile would \n# https:\/\/github.com\/couchbase\/docker\/blob\/master\/enterprise\/couchbase-server\/7.1.1\/Dockerfile#L88\n\n\/entrypoint.sh couchbase-server &amp; \n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The first line starts couchbase server just like the standard docker file would.  We need to do this because docker compose has a limit of only allowing one command\/entrypoint to run per container.  We need couchbase server to start before we can do our automated setup steps.<\/li>\n\n<\/ul>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><strong>NOTE<\/strong> Sleep statements make sure that things complete before moving on to the next step.  The 10-second delay is set after Couchbase Server is started to make sure the cluster is completely running before moving on to the next command.  The delay is conservative and could be shortened based on the speed of your computer.<\/p>\n<\/blockquote>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>sleep 10s  \n\/opt\/couchbase\/bin\/couchbase-cli cluster-init -c 127.0.0.1 \n--cluster-username $COUCHBASE_ADMINISTRATOR_USERNAME \n--cluster-password $COUCHBASE_ADMINISTRATOR_PASSWORD \n--services data,index,query \n--cluster-ramsize $COUCHBASE_RAM_SIZE \n--cluster-index-ramsize $COUCHBASE_INDEX_RAM_SIZE \n--index-storage-setting default\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The couchbase-cli tool is used to initialize the cluster and will set the administration username, password, and services along with the index configuration based on environment variables that are set in the docker compose file we will look at in a bit.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>\/opt\/couchbase\/bin\/couchbase-cli bucket-create -c localhost:8091 \n--username $COUCHBASE_ADMINISTRATOR_USERNAME \n--password $COUCHBASE_ADMINISTRATOR_PASSWORD \n--bucket $COUCHBASE_BUCKET \n--bucket-ramsize $COUCHBASE_BUCKET_RAMSIZE \n--bucket-type couchbase \n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The couchbase-cli tool is used again, but this time to create a bucket bsaed on the environment variables that are set in the docker compose file<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>\/opt\/couchbase\/bin\/couchbase-cli user-manage \n--cluster http:\/\/127.0.0.1 \n--username $COUCHBASE_ADMINISTRATOR_USERNAME \n--password $COUCHBASE_ADMINISTRATOR_PASSWORD \n--set \n--rbac-username $COUCHBASE_RBAC_USERNAME \n--rbac-password $COUCHBASE_RBAC_PASSWORD \n--roles mobile_sync_gateway[*] \n--auth-domain local\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The couchbase-cli tool is used to create a new user that can be used for sync gateway to connect to the server and replicate documents.   The roles switch sets the role for sync gateway and the [*] defines that this user has access to all buckets for sync gateway.  Note this could be a security risk in non-development environments and is set like this for sake of simplicity.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>  \/opt\/couchbase\/bin\/curl -v http:\/\/localhost:8093\/query\/service \n  -u $COUCHBASE_ADMINISTRATOR_USERNAME:$COUCHBASE_ADMINISTRATOR_PASSWORD \n  -d &#039;statement=CREATE INDEX idx_type on userprofile(type)&#039;\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The next command use the REST API to add an index in for queries\nthat you could use in the web console Query in Couchbase Server.  These\naren&#8217;t required for the mobile app or sync, but are nice to have when validating data.<\/li>\n\n<\/ul>\n\n\n\n<h4 id=\"h-sync-gateway-dockerfile\" class=\"wp-block-heading\">Sync Gateway &#8211;  Dockerfile<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Now that we have reviewed how the Couchbase Server will be created, let&#8217;s review how the Sync Gateway server will be created.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Open the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/github.com\/couchbase-examples\/ios-swift-cblite-userprofile-sync\/blob\/main\/src\/sync-gateway\/Dockerfilee\">Dockerfile<\/a> found in the sync-gateway folder in the root of the repo in a text editor of your choice.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>FROM couchbase\/sync-gateway:latest AS stage_base\nCOPY sync-gateway.json \/etc\/sync_gateway\/config.json\nCOPY init-syncgateway.sh \/opt\/couchbase-sync-gateway\/init\/init-syncgateway.sh\n<\/code><\/pre>\n\n\n\n<ol class=\"wp-block-list\">\n<li>The first line tells docker which docker container should be used as the <code>base<\/code> image for this container.  We are using the <code>sync-gateway:latest<\/code> image.<\/li>\n\n\n<li>Next it copies the sync-gateway.json config file into the containers \/etc\/sync_gateway folder and renames it to config.json which Sync Gateway reads in by default when starting.<\/li>\n\n\n<li>Finally, we need a script that will initialize Sync Gateway when the container starts.<\/li>\n\n<\/ol>\n\n\n\n<h5 id=\"h-sync-gateway-config-file-overview\" class=\"wp-block-heading\">Sync Gateway Config File Overview<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">The Sync Gateway server uses a configuration file when it starts to load in all important settings.  In the demo app, this file is setup in <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/sync-gateway\/current\/configuration-properties-legacy.html\">Legacy Pre-3.0 Configuration<\/a> for sake of simplicity.  Let&#8217;s review the configuration file by sections.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Open the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/github.com\/couchbase-examples\/ios-swift-cblite-userprofile-sync\/blob\/main\/src\/sync-gateway\/sync-gateway.json\">sync-gateway.json<\/a> config file found in the same folder as the Dockerfile.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-json\"><code>{\n  &quot;interface&quot;:&quot;:4984&quot;,\n  &quot;adminInterface&quot;:&quot;:4985&quot;,\n   &quot;log&quot;: [&quot;*&quot;],\n  &quot;logging&quot;: {\n    &quot;log_file_path&quot;: &quot;\/var\/tmp\/sglogs&quot;,\n    &quot;console&quot;: {\n      &quot;log_level&quot;: &quot;debug&quot;,\n      &quot;log_keys&quot;: [&quot;*&quot;]\n    },\n    &quot;error&quot;: {\n      &quot;enabled&quot;: true,\n      &quot;rotation&quot;: {\n        &quot;max_size&quot;: 20,\n        &quot;max_age&quot;: 180\n      }\n    },\n    &quot;warn&quot;: {\n      &quot;enabled&quot;: true,\n      &quot;rotation&quot;: {\n        &quot;max_size&quot;: 20,\n        &quot;max_age&quot;: 90\n      }\n    },\n    &quot;info&quot;: {\n      &quot;enabled&quot;: false\n    },\n    &quot;debug&quot;: {\n      &quot;enabled&quot;: true \n    }\n  },\n  &quot;disable_persistent_config&quot;:true,\n  &quot;server_tls_skip_verify&quot;: true,\n  &quot;use_tls_server&quot;: false,\n<\/code><\/pre>\n\n\n\n<ol class=\"wp-block-list\">\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/sync-gateway\/current\/configuration-properties-legacy.html#Interface%20\">interface<\/a> and <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/sync-gateway\/current\/configuration-properties-legacy.html#adminInterface%20\">adminInterface<\/a> are used to define which ports that Sync Gateway will run on.  Note if you change the default values, you will also need to update your mobile app&#8217;s replication configuration.<\/li>\n\n\n<li>log and <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/sync-gateway\/current\/configuration-properties-legacy.html#logging\">logging<\/a> set up the logging configuration.<\/li>\n\n\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/sync-gateway\/current\/configuration-properties-legacy.html#disable_persistent_config\">disable_persistent_config<\/a> is required to run in <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/sync-gateway\/current\/configuration-properties-legacy.html\">Legacy Pre-3.0 Configuration<\/a> mode<\/li>\n\n\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/sync-gateway\/current\/configuration-properties-legacy.html#server_tls_skip_verify\">server_tls_skip_verify<\/a> is set to true because the Couchbase Server container is not using TLS in it&#8217;s configuration.  <strong>NOTE<\/strong>:  DO NOT run with TLS disabled in production!<\/li>\n\n\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/sync-gateway\/current\/configuration-properties-legacy.html#use_tls_server\">use_tls_server<\/a> is set to false so that the mobile app can communicate with the Sync Gateway server over HTTP instead of HTTPS.  This is for the sake of simpliciy.  <strong>NOTE<\/strong>:  DO NOT run with TLS disabled in production!<\/li>\n\n<\/ol>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><strong>Note<\/strong>:  To use TLS with something like self-signed certificates would greatly increase the complexity and length of this tutorial.  For this reason the tutorial shows the configuration without certificates.<\/p>\n<\/blockquote>\n\n\n\n<pre class=\"wp-block-code language-json\"><code>&quot;databases&quot;: {\n    &quot;userprofile&quot;: {\n      &quot;import_docs&quot;: true,\n      &quot;bucket&quot;:&quot;userprofile&quot;,\n      &quot;server&quot;: &quot;couchbase:\/\/couchbase-server&quot;,\n      &quot;enable_shared_bucket_access&quot;:true,\n      &quot;delta_sync&quot;: {\n        &quot;enabled&quot;:false\n      },\n       &quot;num_index_replicas&quot;:0,\n      &quot;username&quot;: &quot;admin&quot;,\n      &quot;password&quot;: &quot;P@ssw0rd&quot;,\n     &quot;users&quot;: { &quot;demo@example.com&quot;: { &quot;password&quot;: &quot;password&quot;},\n                &quot;demo1@example.com&quot;: { &quot;password&quot;: &quot;password&quot;},\n                &quot;demo2@example.com&quot;:{&quot;password&quot;:&quot;password&quot; },\n                &quot;demo3@example.com&quot;:{&quot;password&quot;:&quot;password&quot;},\n                &quot;demo4@example.com&quot;:{&quot;password&quot;:&quot;password&quot;}\n              },\n<\/code><\/pre>\n\n\n\n<ol class=\"wp-block-list\">\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/sync-gateway\/current\/configuration-properties-legacy.html#databases\">databases<\/a>  sets up the configuration for communication between Sync Gateway and Couchbase Server.<\/li>\n\n\n<li>userprofile is the configuration section for the userprofile bucket that Sync Gateway will be replicating.<\/li>\n\n\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/sync-gateway\/current\/configuration-properties-legacy.html#databases\">import_docs<\/a> set to true allows Sync Gateway to import documents that exists on Couchbase Server.<\/li>\n\n\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/sync-gateway\/current\/configuration-properties-legacy.html#databases-this_db-bucket\">bucket<\/a> is the name of the bucket that Sync Gateway will replicate with on Couchbase Server.<\/li>\n\n\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/sync-gateway\/current\/configuration-properties-legacy.html#databases-this_db-server\">server<\/a> is the connection string to connect to the Couchbase Server.  The name of the server is defined in the Docker Compose file and dockers internal DNS will handle name resolution to this hostname.<\/li>\n\n\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/sync-gateway\/current\/configuration-properties-legacy.html#databases-this_db-enable_shared_bucket_access\">enable_shared_bucket_access<\/a> enables Mobile-Server Data Sync (a.ka. mobile convergence), which will generate the mobile-specific metadata for all the preexisting documents in the Couchbase Server bucket.  You can learn more about this functionality in <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/sync-gateway\/current\/sync-with-couchbase-server.html\">Syncing Mobile and Server<\/a> documentation.<\/li>\n\n\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/sync-gateway\/current\/configuration-properties-legacy.html#databases-this_db-delta_sync\">delta_sync<\/a> is an Enterprise Edition feature which requires a license.  Delta Sync allows Sync Gateway to replicate only the parts of the Couchbase Mobile document that have changed.<\/li>\n\n\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/sync-gateway\/current\/configuration-properties-legacy.html#databases-this_db-num_index_replicas\">num_index_replicas<\/a> determines the number of index replicas used when creating the core Sync Gateway indexes.<\/li>\n\n\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/sync-gateway\/current\/configuration-properties-legacy.html#databases-this_db-replications-this_rep-username\">username<\/a> Sync Gateway uses to connect to the Couchbase Server.  This username was created in the automation shell script step.<\/li>\n\n\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/sync-gateway\/current\/configuration-properties-legacy.html#databases-this_db-password\">password<\/a> is the password that Sync Gateway will use to communicate with Couchbase Server.<\/li>\n\n\n<li><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/sync-gateway\/current\/configuration-properties-legacy.html#databases-this_db-users\">users<\/a> is a hard coded collection of username, passwords and the role that the user is assigned to.  Roles can be assigned to channels to which documents are assigned to in the sync process, restricting the documents that are replicated.  Note that these username and passwords are the same username and passwords that are hard coded into the in the mobile app.<\/li>\n\n\n<li><\/li>\n\n<\/ol>\n\n\n\n<h5 id=\"h-sync-function\" class=\"wp-block-heading\">Sync Function<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">The sync section of the configuration is used to define custom business logic.  The sync is a string value of Javascript code that will run every time a new document, revision, or deletion is added to a database.  The sync function will examine the document and custom business logic can then calculate things like access control to limit which users can see which documents.  The demo app is a simple example of custom business logic.  See the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/sync-gateway\/current\/sync-function-api.html\">Sync Function API<\/a> and <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/sync-gateway\/current\/access-control-how.html\">Access Control How-To<\/a> guides for more detailed information and a listing of other API functions available.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>function sync(doc, oldDoc) {\n    console.log(&quot;********Procesing Doc. Is oldDoc == null? &quot; + (oldDoc == null));\n\n    \/* Data Validation *\/\n    \/\/ Validate the presence of email field.\n    \/\/ This is the &quot;username&quot; &lt;.&gt;\n    validateNotEmpty(&quot;email&quot;, doc.email);\n\n    \/\/ Validate that the document Id _id is prefixed by owner &lt;.&gt;\n    var expectedDocId = &quot;user&quot; + &quot;::&quot; + doc.email;\n    if (expectedDocId != doc._id) {\n      \/\/ reject document\n      throw({forbidden: &quot;user doc Id must be of form user::email&quot;});\n    }\n   try {\n\n       \/\/ Check if this is an import processing (done with admin credentials)\n       requireAdmin();\n       if (!isDelete()) {\n           \/* Routing *\/\n\n           var username = getEmail();\n           var channelId = &quot;channel.&quot;+ username;\n\n           channel(channelId);\n\n           \/\/ Give user access to document\n           access(username,channelId);\n        }\n    }catch (error) {\n       console.log(&quot;This is not a doc import &quot; + error);\n\n       \/\/ If non admin client replication\n       if (!isDelete()) {\n\n         \/* Authorization *\/\n         \/\/ Verify the user making the request is the same as the one in doc&#039;s email\n         requireUser(doc.email);\n\n         \/\/ Check if document is being created \/ added for first time\n         \/\/ We allow any user to create the document\n         if (isCreate()) {\n            \/* Routing *\/\n            \/\/ Add doc to the user&#039;s channel.\n            var username = getEmail(); \n            var channelId = &quot;channel.&quot;+ username; \n            channel(channelId); \n\n            \/\/ Give user access to document \n            access(username, channelId);\n\n          } else {\n              \/\/ This is an update\n              \/\/ Validate that the email hasn&#039;t changed.\n              validateReadOnly(&quot;email&quot;, doc.email, oldDoc.email);\n              \/\/ Add doc to the user&#039;s channel.\n              var username = getEmail();\n              var channelId = &quot;channel.&quot;+ username;\n\n              channel(channelId);\n\n              \/\/ Give user access to document\n              access(username,channelId);\n          }\n       }\n    }\n  \/\/ get type property\n  function getType() {\n    return (isDelete() ? oldDoc.type : doc.type);\n  }\n\n  \/\/ get email Id property\n  function getEmail() {\n    return (isDelete() ? oldDoc.email : doc.email);\n  }\n\n  \/\/ Check if document is being created\/added for first time\n  function isCreate() {\n    \/\/ Checking false for the Admin UI to work\n    return ((oldDoc == false) || (oldDoc == null || oldDoc._deleted) &amp;&amp; !isDelete());\n  }\n\n  \/\/ Check if this is a document update\n  function isUpdate() {\n    return (!isCreate() &amp;&amp; !isDelete());\n  }\n\n  \/\/ Check if this is a document delete\n  function isDelete() {\n    return (doc._deleted == true);\n  }\n\n  \/\/ Verify that specified property exists\n  function validateNotEmpty(key, value) {\n    if (!value) {\n      throw({forbidden: key + &quot; is not provided.&quot;});\n    }\n  }\n\n  \/\/ Verify that specified property value has not changed during update\n  function validateReadOnly(name, value, oldValue) {\n    if (value != oldValue) {\n      throw({forbidden: name + &quot; is read-only.&quot;});\n    }\n  }\n}\n<\/code><\/pre>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Locate the <em><code>\/\/ Authorization<\/code><\/em> section of the Sync Function.  You will see we are using the Sync functions <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/developer.couchbase.com\/documentation\/mobile\/2.0\/guides\/sync-gateway\/sync-function-api-guide\/index.html#requireuserusername\"><code>requireUser()<\/code><\/a> API to verify that the <code>email<\/code> property specified in the Document matches the Id of the user making the request.<\/li>\n\n\n<li>Data validation is done via the validateNotEmpy function by inspecting some of the contents of the document.<\/li>\n\n\n<li>Verify that the <code>email<\/code> property is not null. If it&#8217;s null, we throw a JS exception (see <code>validateNotEmpty()<\/code> function)<\/li>\n\n\n<li>If this a new document, then verify that the <code>Id<\/code> of the Document is of the required format (i.e. <strong><em>&#8220;user::&lt;email&gt;&#8221;<\/em><\/strong>). We throw an exception if that&#8217;s not the case.<\/li>\n\n\n<li>If this is a document update, then verify that the <code>email<\/code> property value has not changed. Again, we throw an exception if that&#8217;s not the case.<\/li>\n\n<\/ol>\n\n\n\n<h4 id=\"h-docker-compose-yaml-file\" class=\"wp-block-heading\">Docker Compose YAML file<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/github.com\/couchbase-examples\/ios-swift-cblite-userprofile-sync\/blob\/main\/docker-compose.yml\">docker-compose.yml<\/a> file is provide to configure and build the Couchbase Server and Sync Gateway containers that we have reviewed.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Open the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/github.com\/couchbase-examples\/ios-swift-cblite-userprofile-sync\/blob\/main\/docker-compose.yml\">docker-compose.yml<\/a> found in the root of the repo in a text editor of your choice.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-yaml\"><code>couchbase-server-ios-userprofile:\n  build: .\/src\/couchbase-server\n  ports:\n    - 8091-8097:8091-8097\n    - 9123:9123\n    - 11207:11207\n    - 11210:11210\n    - 11280:11280\n    - 18091-18097:18091-18097\n  environment:\n    - CLUSTER_NAME=couchbase-demo\n    - COUCHBASE_ADMINISTRATOR_USERNAME=Administrator\n    - COUCHBASE_ADMINISTRATOR_PASSWORD=P@ssw0rd12\n    - COUCHBASE_BUCKET=userprofile\n    - COUCHBASE_BUCKET_RAMSIZE=512\n    - COUCHBASE_RBAC_USERNAME=admin\n    - COUCHBASE_RBAC_PASSWORD=P@ssw0rd\n    - COUCHBASE_RBAC_NAME=admin\n    - COUCHBASE_RAM_SIZE=2048\n    - COUCHBASE_INDEX_RAM_SIZE=512\n  hostname: couchbase-server\n  container_name: couchbase-server-ios-userprofile\n  working_dir: \/opt\/couchbase\n  stdin_open: true\n  tty: true\n  networks:\n    - workshop\n  entrypoint: [&quot;&quot;]\n  command: sh -c &quot;\/opt\/couchbase\/init\/init-cbserver.sh&quot;\n<\/code><\/pre>\n\n\n\n<ol class=\"wp-block-list\">\n<li>The couchbase-server-ios-userprofile section is used to define the couchbase server container.<\/li>\n\n\n<li>The build property defines what directory to look for the Dockerfile in<\/li>\n\n\n<li>The ports collection defines the ports that Couchbase Server requires to run<\/li>\n\n\n<li>The environment collection defines a set of environment variables that we use in our automation shell script to setup Couchbase Server<\/li>\n\n\n<li>The hostname defines what name should be used for DNS resolution<\/li>\n\n\n<li>The working directory will be used for all commands ran.  We default this to \/opt\/couchbase since our automation script and data import file are located in this directory<\/li>\n\n\n<li>The network is set to workshop which will define a bridge or shared network that can be used to allow the Couchbase Server to communicate with the Sync Gateway server<\/li>\n\n\n<li>The entrypoint property is set to blank and overridden with a command since we want to run our custom automation script when the container is built.<\/li>\n\n<\/ol>\n\n\n\n<pre class=\"wp-block-code language-yaml\"><code>sync-gateway-ios-userprofile:\n    build: .\/src\/sync-gateway\n    ports:\n      - 4984-4986:4984-4986\n    hostname: sync-gateway\n    container_name: sync-gateway-ios-userprofile\n    depends_on:\n      - couchbase-server-ios-userprofile \n    working_dir: \/docker-syncgateway\n    stdin_open: true\n    tty: true      \n    networks:\n      - workshop\n    entrypoint: [&quot;&quot;]\n    command: sh -c &quot;\/opt\/couchbase-sync-gateway\/init\/init-syncgateway.sh&quot;\n<\/code><\/pre>\n\n\n\n<ol class=\"wp-block-list\">\n<li>The sync-gateway-ios-userprofile section is used to define the sync gateway server container.<\/li>\n\n\n<li>The build property defines what directory to look for the Dockerfile in<\/li>\n\n\n<li>The ports collection defines the ports that Sync Gateway requires to run<\/li>\n\n\n<li>The hostname defines what name should be used for DNS resolution<\/li>\n\n\n<li>The network is set to workshop which will define a bridge or shared network that can be used to allow the Couchbase Server to communicate with the Sync Gateway server<\/li>\n\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">Finally, we define the network configuration and driver to use.<\/p>\n\n\n\n<pre class=\"wp-block-code language-yaml\"><code>networks:\n  workshop:\n    driver: bridge\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-try-docker-compose\" class=\"wp-block-heading\">Try Docker Compose<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Now that we have reviewed all the files that are used to create the containers, open a terminal window.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Make sure you are in the root directory of the repo<\/li>\n\n\n<li>Run the docker-compose command<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>docker-compose up -d\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>\n<p>The docker containers should start downloading, then build, and finally start up<\/p>\n<\/li>\n\n\n<li>\n<p>You can check the status of docker using either Docker Desktop or the terminal commands.<\/p>\n<\/li>\n\n\n<li>\n<p>Docker Desktop Users should see a container listing after launching the app.  The group name of the containers is\nthe name of the directory of the code repo on your computer where you ran docker compose of. In the example it&#8217;s named <code>ios-swift-cblite-userprofile-sync<\/code>.<\/p>\n<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><img decoding=\"async\" src=\"docker-desktop.png\" alt=\"Docker Desktop\" title=\"#width=600px\"><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Terminal users can use the docker-compose command to see the containers status<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>docker-compose ls\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><img decoding=\"async\" src=\"docker-compose-ls.png\" alt=\"Docker Compose Terminal \" title=\"#width=800px\"><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>To see individual containers you can use the docker command<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>docker container ls\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><img decoding=\"async\" src=\"docker-ls.png\" alt=\"Docker Terminal \" title=\"#width=800px\"><\/p>\n\n\n\n<h5 id=\"h-validation-of-containers\" class=\"wp-block-heading\">Validation of Containers<\/h5>\n\n\n\n<ul class=\"wp-block-list\">\n<li>\n<p>Docker Desktop Users can select each container in Docker Desktop to get detained information and logs about the container running to validate the containers were built properly or use the terminal to gather information.<\/p>\n<\/li>\n\n\n<li>\n<p>Docker Desktop Users &#8211; select the couchbase-server-ios-userprofile container.  You should see logging information.<\/p>\n<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><img decoding=\"async\" src=\"docker-couchbase-server-logs.png\" alt=\"Docker Desktop\" title=\"#width=800px\"><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Terminal users can enter the following command<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>docker container logs couchbase-server-ios-userprofile\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The logs should show the status of cluster initialization, bucket creation, and User admin.  This will be followed\nby the results of the curl commands that create the index.  When the setup is complete, you should see output similar to that shown below:<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-logs\"><code>Administrator : P@ssw0rd12\nStarting Couchbase Server -- Web UI available at http:\/\/&lt;ip&gt;:8091\nand logs available in \/opt\/couchbase\/var\/lib\/couchbase\/logs\nSUCCESS: Cluster initialized\nSUCCESS: Bucket created\nSUCCESS: User admin set\n*   Trying 127.0.0.1:8093...\n* Connected to localhost (127.0.0.1) port 8093 (#0)\n* Server auth using Basic with user &#039;Administrator&#039;\n&gt; POST \/query\/service HTTP\/1.1\n&gt; Host: localhost:8093\n&gt; Authorization: Basic QWRtaW5pc3RyYXRvcjpQQHNzdzByZDEy\n&gt; User-Agent: curl\/7.84.0-DEV\n&gt; Accept: *\/*\n&gt; Content-Length: 52\n&gt; Content-Type: application\/x-www-form-urlencoded\n&gt;\n* Mark bundle as not supporting multiuse\n&lt; HTTP\/1.1 200 OK\n&lt; Content-Length: 238\n&lt; Content-Type: application\/json; version=7.2.0-N1QL\n&lt; Date: Mon, 21 Aug 2023 11:23:19 GMT\n&lt;\n{\n&quot;requestID&quot;: &quot;bc6471ad-edbe-4ee2-a030-dd260ecef3cb&quot;,\n&quot;signature&quot;: null,\n&quot;results&quot;: [\n],\n&quot;status&quot;: &quot;success&quot;,\n&quot;metrics&quot;: {&quot;elapsedTime&quot;: &quot;1.650022084s&quot;,&quot;executionTime&quot;: &quot;1.649861501s&quot;,&quot;resultCount&quot;: 0,&quot;resultSize&quot;: 0,&quot;serviceLoad&quot;: 5}\n}\n* Connection #0 to host localhost left intact\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Docker Desktop Users &#8211; click the back button and now select the sync-gateway container.  You should see logging information.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><img decoding=\"async\" src=\"docker-sync-gateway-logs.png\" alt=\"Docker Desktop\" title=\"#width=800px\"><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Terminal users can enter the following command<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>docker container logs sync-gateway-ios-userprofile\n<\/code><\/pre>\n\n\n\n<h5 id=\"h-validate-sync-gateway-server\" class=\"wp-block-heading\">Validate Sync Gateway Server<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">To validate the Sync Gateway server we will use the REST API interface.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Open up <a href=\"http:\/\/localhost:4984\">http:\/\/localhost:4984<\/a> in your web browser.  You should see equivalent of the following message (your\nversion of Sync Gateway might be newer than the text below):<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-json\"><code>{&quot;couchdb&quot;:&quot;Welcome&quot;,&quot;vendor&quot;:{&quot;name&quot;:&quot;Couchbase Sync Gateway&quot;,&quot;version&quot;:&quot;3.0&quot;},&quot;version&quot;:&quot;Couchbase Sync Gateway\/3.0.0(541;46803d1) EE&quot;}\n<\/code><\/pre>\n\n\n\n<h3 id=\"h-starting-replication\" class=\"wp-block-heading\">Starting Replication<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Two-way Replication between the app and the Sync Gateway is enabled when user logs into the app.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To see the code behind this, open the project&#8217;s <strong>DatabaseManager.swift<\/strong> file and locate the <code>startPushAndPullReplicationForCurrentUser()<\/code> function.<\/p>\n\n\n\n<pre class=\"wp-block-code language-swift\"><code>func startPushAndPullReplicationForCurrentUser() {\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In the function you will see we create an instance of the <code>ReplicatorConfig<\/code>, which specifies the source and target database.  You could also use this to, optionally, override the default configuration settings.<\/p>\n\n\n\n<pre class=\"wp-block-code language-swift\"><code>let dbUrl = remoteUrl.appendingPathComponent(kDBName)\nlet config = ReplicatorConfiguration.init(database: db, target: URLEndpoint.init(url:dbUrl)) \n\nconfig.replicatorType = .pushAndPull\nconfig.continuous =  true \nconfig.authenticator =  BasicAuthenticator(username: user, password: password) \n\n\/\/ This should match what is specified in the sync gateway config\n\/\/ Only pull documents from this user&#039;s channel\nlet userChannel = &quot;channel.(user)&quot;\nconfig.channels = [userChannel]\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>\n<p>Initialize with <code>source<\/code> as the local Couchbase Lite database and the <code>remote<\/code> target as the Sync Gateway<\/p>\n<\/li>\n\n\n<li>\n<p>Replication <code>type<\/code> of <code>pushAndPull<\/code> indicates that we require two-way sync. A value of <code>.pull<\/code> specifies that we only pull data from the Sync Gateway. A value of <code>.push<\/code> specifies that we only push data.<\/p>\n<\/li>\n\n\n<li>\n<p>The <code>continuous<\/code> mode is specified to be <em>true<\/em> which means that changes are synced in real-time. A value of <em>false<\/em>  which implies that data is only pulled from the Sync Gateway.<\/p>\n<\/li>\n\n\n<li>\n<p>This is where you specify the authentication credentials of the user. In the <a href=\"#authorization\">Authorization<\/a> section, we discussed that the Sync Gateway can enforce authorization check using the <code>requireUser<\/code> API.<\/p>\n<\/li>\n\n\n<li>\n<p>The <code>channels<\/code> are used to specify the channels to pull from. Only documents belonging to the specified channels are synced. This is subject to Access Control rights enforced at the Sync Gateway. This means that if a client does not have access to documents in a channel, the documents will not be synched even if the client specifies it in the replicator configuration.<\/p>\n<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Now we initialize the <code>Replicator<\/code> with the <code>ReplicatorConfiguration<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-swift\"><code>_pushPullRepl = Replicator.init(config: config)\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In order to follow the replicators progress, we can attach a callback listener to it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Attaching a callback listener to the <code>Replicator<\/code> means we will be asynchronously notified of state changes.\nThis could be useful for instance, to inform the user of the progress of the replication.  It is an optional step shown below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-swift\"><code>_pushPullReplListener = _pushPullRepl?.addChangeListener({ (change) in\n  let s = change.status\n  switch s.activity {\n    case .busy:\n      print(&quot;Busy transferring data&quot;)\n    case .connecting:\n      print(&quot;Connecting to Sync Gateway&quot;)\n    case .idle:\n      print(&quot;Replicator in Idle state&quot;)\n    case .offline:\n      print(&quot;Replicator in offline state&quot;)\n    case .stopped:\n      print(&quot;Completed syncing documents&quot;)\n  }\n})\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Now, with all that done, we can start the replicator.\u2009<\/p>\n\n\n\n<pre class=\"wp-block-code language-swift\"><code>_pushPullRepl?.start()\n<\/code><\/pre>\n\n\n\n<h3 id=\"h-stopping-replication\" class=\"wp-block-heading\">Stopping Replication<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">When user logs out of the app, the replication is stopped before the database is closed.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Open the <em>DatabaseManager.swift<\/em> file and locate the <code>stopAllReplicationForCurrentUser()<\/code> function.<\/li>\n\n<\/ol>\n\n\n\n<pre class=\"wp-block-code language-swift\"><code>func stopAllReplicationForCurrentUser() {\n<\/code><\/pre>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Stop the replicator and remove any associated change listeners<\/li>\n\n<\/ol>\n\n\n\n<pre class=\"wp-block-code language-swift\"><code>if let pushPullReplListener = _pushPullReplListener{\n  print(#function)\n  _pushPullRepl?.removeChangeListener(withToken:  pushPullReplListener)\n  _pushPullRepl = nil\n  _pushPullReplListener = nil\n}\n_pushPullRepl?.stop()\n<\/code><\/pre>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><strong>TIP<\/strong>: When you close a database, any active replicators, listeners and-or live queries are also be closed.<\/p>\n<\/blockquote>\n\n\n\n<h3 id=\"h-query-events-live-queries\" class=\"wp-block-heading\">Query Events \/ Live Queries<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Couchbase Lite applications can set up <strong>live queries<\/strong> in order to be asynchronously notified of changes to the database that affect the results of the query.  This can be very useful, for instance, in keeping a UI View up-to-date with the results of a query.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In our app, the user profile view is kept up-to-date using a live query that fetches the user profile data used to populate the view.  This means that, if the replicator pulls down changes to the user profile, they are automatically reflected in the view.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To see this:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Open the <em>UserPresenter.swift<\/em> file and locate the <code>fetchRecordForCurrentUserWithLiveModeEnabled()<\/code> function. Calling this function with a value of <code>true<\/code> implies that the caller wishes to be notified of any changes to query results.<\/li>\n\n<\/ol>\n\n\n\n<pre class=\"wp-block-code language-swift\"><code>func fetchRecordForCurrentUserWithLiveModeEnabled(__ enabled:Bool = false) {\n<\/code><\/pre>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Build the Query using <code>QueryBuilder<\/code> API. If you are unfamiliar with this API, please check out the <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/developer.couchbase.com\/tutorial-quickstart-ios-uikit-query\">Quickstart in Couchbase Lite Query with iOS, Swift, and UIKit<\/a> tutorial.<\/li>\n\n<\/ol>\n\n\n\n<pre class=\"wp-block-code language-swift\"><code>guard let db = dbMgr.db else {\n  fatalError(&quot;db is not initialized at this point!&quot;)\n}\nuserQuery = QueryBuilder\n  .select(SelectResult.all())\n  .from(DataSource.database(db))\n  .where(Meta.id.equalTo(Expression.string(self.userProfileDocId)))\n<\/code><\/pre>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><strong>Note<\/strong>: We query for documents based on document Id. In our app, there should be exactly one user profile document corresponding to this Id.<\/p>\n<\/blockquote>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Attach listener callback to the query to make it <strong>live<\/strong>.<\/li>\n\n<\/ol>\n\n\n\n<pre class=\"wp-block-code language-swift\"><code>userQueryToken = userQuery?.addChangeListener { [weak self] (change) in \n  guard let `self`` = self else {return}\n  switch change.error {\n    case nil:\n      var userRecord = UserRecord.init()\n      userRecord.email = self.dbMgr.currentUserCredentials?.user\n      \n      for (_, row) in (change.results?.enumerated())! {\n        if let userVal = row.dictionary(forKey: &quot;userprofile&quot;) { \n          userRecord.email  =  userVal.string(forKey: UserRecordDocumentKeys.email.rawValue)\n          userRecord.address = userVal.string(forKey:UserRecordDocumentKeys.address.rawValue)\n          userRecord.name =  userVal.string(forKey: UserRecordDocumentKeys.name.rawValue)\n          userRecord.university = userVal.string(forKey: UserRecordDocumentKeys.university.rawValue)\n          userRecord.imageData = userVal.blob(forKey:UserRecordDocumentKeys.image.rawValue)?.content \n        }\n      }\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>\n<p>Attach a listener callback to the query. Attaching a listerner automatically makes it <strong>live<\/strong> so any time there is a change in the user profile data in the underlying database, the callback would be invoked<\/p>\n<\/li>\n\n\n<li>\n<p>Create an instance of UserRecord. This will be populated with the query results.<\/p>\n<\/li>\n\n\n<li>\n<p>The <code>SelectResult.all()<\/code> method is used to query all the properties of a document. In this case, the document in the result is embedded in a dictionary where the key is the database name, which is <strong>&#8220;userprofile&#8221;<\/strong>. So we retrieve the <a target=\"_blank\" rel=\"noopener noreferrer\" ref=\"https:\/\/docs.couchbase.com\/mobile\/3.0.0-beta02\/couchbase-lite-swift\/Classes\/DictionaryObject.html\">DictionaryObject<\/a> at key <strong><em>&#8220;userprofile&#8221;<\/em><\/strong>.<\/p>\n<\/li>\n\n\n<li>\n<p>We use appropriate <em>type getters<\/em> to retrieve values and populate the <em>UserRecord<\/em> instance<\/p>\n<\/li>\n\n<\/ul>\n\n\n\n<h3 id=\"h-exercises\" class=\"wp-block-heading\">Exercises<\/h3>\n\n\n\n<h4 id=\"h-exercise-1\" class=\"wp-block-heading\">Exercise 1<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">In this exercise, we will observe how changes made on one app are synced across to the other app<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>The app should be running in two simulators side by side.<\/li>\n\n\n<li>Log into both the simulators with same userId and password. Use the values <strong><a href=\"mailto:demo@example.com\">demo@example.com<\/a><\/strong> and <strong>password<\/strong> for user Id and password fields respectively.<\/li>\n\n\n<li>On one simulator, enter values in the user and address fields.<\/li>\n\n\n<li>Confirm that changes show up in the app on the other simulator.<\/li>\n\n\n<li>Similarly, make changes to the app in the other simulator and confirm that the changes are synced over to the first simulator.<\/li>\n\n<\/ol>\n\n\n\n<h4 id=\"h-exercise-2\" class=\"wp-block-heading\">Exercise 2<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">In this exercise, we will observe changes made via Sync Gateway are synced over to the apps<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>\n<p>Make sure you have completed Exercise 1. This is to ensure that you have the appropriate user profile document (with document Id of &#8220;user::<a href=\"mailto:demo@example.com\">demo@example.com<\/a>&#8220;) created through the app and synced over to the Sync Gateway.<\/p>\n<\/li>\n\n\n<li>\n<p>Open the command terminal and issue the following command to get the user profile document via link:[GET Document REST API] . We will be using <code>curl<\/code> to issue the request. If you haven&#8217;t done so, please install curl as indicated in the Prerequisites section.<\/p>\n<\/li>\n\n<\/ol>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>curl -X GET http:\/\/localhost:4984\/userprofile\/user::demo@example.com --user demo@example.com\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>This GET retrieves the userprofile document with the id <strong>user::<a href=\"mailto:demo@example.com\">demo@example.com<\/a><\/strong><\/li>\n\n<\/ul>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Your response should look something like the response below. The exact contents depends on the user profile information that you provided via your mobile app.<\/li>\n\n<\/ol>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>{\n    &quot;_attachments&quot;: { \n        &quot;blob_1&quot;: {\n            &quot;content_type&quot;: &quot;image\/jpeg&quot;,\n            &quot;digest&quot;: &quot;sha1-S8asPSgzA+F+fp8\/2DdIy4K+0U8=&quot;,\n            &quot;length&quot;: 14989,\n            &quot;revpos&quot;: 2,\n            &quot;stub&quot;: true\n        }\n    },\n    &quot;_id&quot;: &quot;user::demo@example.com&quot;,\n    &quot;_rev&quot;: &quot;2-3a76cfa911e2c54d1e82b29dbffc7f4e5a9bc265&quot;, \n    &quot;address&quot;: &quot;&quot;,\n    &quot;email&quot;: &quot;demo@example.com&quot;,\n    &quot;image&quot;: { \n        &quot;@type&quot;: &quot;blob&quot;,\n        &quot;content_type&quot;: &quot;image\/jpeg&quot;,\n        &quot;digest&quot;: &quot;sha1-S8asPSgzA+F+fp8\/2DdIy4K+0U8=&quot;,\n        &quot;length&quot;: 14989\n    },\n    &quot;name&quot;: &quot;&quot;,\n    &quot;type&quot;: &quot;user&quot;,\n    &quot;university&quot;: &quot;British Institute in Paris, University of London&quot;\n}\n<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li>\n<p>If you had updated an image via the mobile app, you should see an <strong>&#8220;_attachments&#8221;<\/strong> property. This entry holds an array of attachments corresponding to each image blob entry added by the mobile app. This property is added by the Sync Gateway when it processes the document. You can learn more about how image Blob types are mapped to attachments <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/couchbase-lite\/3.0\/swift\/blob.html\">here<\/a>.<\/p>\n<\/li>\n\n\n<li>\n<p>Record the revision Id of the document.  You will need this when you update the document<\/p>\n<\/li>\n\n<\/ul>\n\n\n\n<ol class=\"wp-block-list\">\n<li>In the command terminal, issue the following command to update the user profile document via <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/sync-gateway\/3.0\/rest-api.html#\/document\/AddOrUpdateDocument\">PUT Document REST API<\/a>.<\/li>\n\n<\/ol>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><strong>NOTE<\/strong>: We chose to show how to update the address field via the REST API.  You can choose to update any other profile information if you like.  You will be prompted to enter the users password when you submit the curl command.<\/p>\n<\/blockquote>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>curl -X PUT \n  &#039;http:\/\/localhost:4985\/userprofile\/user::demo@example.com?rev=3-12d203d6024c8b844c5ed736c726ac63379e05dc&#039; \n  -H &#039;Accept: application\/json&#039; \n  -H &#039;Cache-Control: no-cache&#039; \n  -H &#039;Content-Type: application\/json&#039; \n  -d &#039;{\n    &quot;address&quot;: &quot;101 Main Street&quot;, \n    &quot;email&quot;: &quot;demo@example.com&quot;,\n    &quot;image&quot;: {\n        &quot;@type&quot;: &quot;blob&quot;,\n        &quot;content_type&quot;: &quot;image\/jpeg&quot;,\n        &quot;digest&quot;: &quot;sha1-S8asPSgzA+F+fp8\/2DdIy4K+0U8=&quot;,\n        &quot;length&quot;: 14989\n    },\n    &quot;name&quot;: &quot;&quot;,\n    &quot;type&quot;: &quot;user&quot;,\n    &quot;university&quot;: &quot;British Institute in Paris, University of London&quot;\n}&#039;\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here, in the <code>PUT<\/code>, we specify the:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>user id (<code>user::demo@example.com<\/code>)<\/li>\n\n\n<li>revision Id (from the previous step <code>3-033fcbaf269d65a9247067be76d664f1111d033b<\/code>) to select the item we want to update<\/li>\n\n<\/ul>\n\n\n\n<ol class=\"wp-block-list\">\n<li>\n<p>Confirm that you get a HTTP <em>&#8220;201 Created&#8221;<\/em> status code<\/p>\n<\/li>\n\n\n<li>\n<p>As soon as you update the document via the Sync Gateway REST API, confirm that the changes show up in the mobile app on the simulator.<\/p>\n<\/li>\n\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\"><img decoding=\"async\" src=\".\/sync_from_sgw.gif\" alt=\"App Sync\"><\/p>\n\n\n\n<h3 id=\"h-handling-conflicts-during-data-syncronization\" class=\"wp-block-heading\">Handling Conflicts during Data Syncronization<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Data conflicts are inevtiable in an environment where you can potentially have multiple writes updating the same data concurrently. Couchbase Mobile supports <strong><em>Automated Conflict Resolution<\/em><\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can learn more about automated conflict resolution in this blog <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/blog.couchbase.com\/document-conflicts-couchbase-mobile\/\">Document Conflicts &amp; Resolution<\/a>.<\/p>\n\n\n\n<h3 id=\"h-learn-more\" class=\"wp-block-heading\">Learn More<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Congratulations on completing this tutorial!<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This tutorial walked you through an example of how to use a Sync Gateway to synchronize data between Couchbase Lite enabled clients. We discussed how to configure your Sync Gateway to enforce relevant access control, authorization and data routing between Couchbase Lite enabled clients.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Check out the following links for further details.<\/p>\n\n\n\n<h4 id=\"h-further-reading\" class=\"wp-block-heading\">Further Reading<\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/docs.couchbase.com\/sync-gateway\/3.0\/configuration-overview.html\">Sync Gateway Configuration<\/a><\/p>\n<\/li>\n\n\n<li>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/blog.couchbase.com\/category\/couchbase-mobile\/?ref=blog-menu\">Couchbase Mobile Blog<\/a><\/p>\n<\/li>\n\n\n<li>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/blog.couchbase.com\/?s=sync+function\">Sync function blogs<\/a><\/p>\n<\/li>\n\n\n<li>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/blog.couchbase.com\/data-replication-couchbase-mobile\/\">Overview of Replication Protocol<\/a><\/p>\n<\/li>\n\n\n<li>\n<p><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\/\/blog.couchbase.com\/document-conflicts-couchbase-mobile\/\">Document Conflicts &amp; Resolution<\/a><\/p>\n<\/li>\n\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Introduction Couchbase Sync Gateway is a key component of the Couchbase Mobile stack. It is an Internet-facing synchronization mechanism that securely syncs data across devices as well as between devices and the cloud. Couchbase Mobile uses a websocket based replication protocol. The core functions of the Sync Gateway include This tutorial will demonstrate how to &#8211; We will be using a Swift App as an example of a Couchbase Lite enabled client. You can learn more about the Sync Gateway here in the Sync Gateway Documentation. Prerequisites This tutorial assumes familiarity with building swift apps with Xcode and with Couchbase Lite. Note: If you are using an older version of [&hellip;]<\/p>\n","protected":false},"author":0,"featured_media":0,"menu_order":0,"template":"","meta":{"_acf_changed":false,"_acf":"","inline_featured_image":false,"footnotes":""},"tutorial-languages":[594],"tutorial-tags":[590],"tutorial-technologies":[548,585,549,597],"tutorial-types":[550],"class_list":["post-10274","tutorials","type-tutorials","status-publish","hentry","tutorial-languages-swift","tutorial-tags-ios","tutorial-technologies-kv","tutorial-technologies-mobile","tutorial-technologies-query","tutorial-technologies-sync-gateway","tutorial-types-quickstart"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v28.9 (Yoast SEO v28.9) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>Quickstart in Couchbase Lite Data Sync with iOS, Swift, and UIKit - Couchbase<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.couchbase.com\/ja\/developers\/tutorials\/quickstart-ios-uikit-sync\/\" \/>\n<meta property=\"og:locale\" content=\"ja_JP\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Quickstart in Couchbase Lite Data Sync with iOS, Swift, and UIKit\" \/>\n<meta property=\"og:description\" content=\"Introduction Couchbase Sync Gateway is a key component of the Couchbase Mobile stack. It is an Internet-facing synchronization mechanism that securely syncs data across devices as well as between devices and the cloud. Couchbase Mobile uses a websocket based replication protocol. The core functions of the Sync Gateway include This tutorial will demonstrate how to &#8211; We will be using a Swift App as an example of a Couchbase Lite enabled client. You can learn more about the Sync Gateway here in the Sync Gateway Documentation. Prerequisites This tutorial assumes familiarity with building swift apps with Xcode and with Couchbase Lite. Note: If you are using an older version of [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.couchbase.com\/ja\/developers\/tutorials\/quickstart-ios-uikit-sync\/\" \/>\n<meta property=\"og:site_name\" content=\"Couchbase\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/Couchbase\/\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/10\/Cloud-2.png\" \/>\n\t<meta property=\"og:image:width\" content=\"2548\" \/>\n\t<meta property=\"og:image:height\" content=\"1171\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:site\" content=\"@couchbase\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"30\u5206\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/ja\\\/developers\\\/tutorials\\\/quickstart-ios-uikit-sync\\\/\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/ja\\\/developers\\\/tutorials\\\/quickstart-ios-uikit-sync\\\/\",\"name\":\"Quickstart in Couchbase Lite Data Sync with iOS, Swift, and UIKit - Couchbase\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/ja\\\/#website\"},\"datePublished\":\"2023-08-28T13:56:25+00:00\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/ja\\\/developers\\\/tutorials\\\/quickstart-ios-uikit-sync\\\/#breadcrumb\"},\"inLanguage\":\"ja\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.couchbase.com\\\/ja\\\/developers\\\/tutorials\\\/quickstart-ios-uikit-sync\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/ja\\\/developers\\\/tutorials\\\/quickstart-ios-uikit-sync\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.couchbase.com\\\/ko\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Quickstart in Couchbase Lite Data Sync with iOS, Swift, and UIKit\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/ja\\\/#website\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/ja\\\/\",\"name\":\"Couchbase\",\"description\":\"The Operational Data Platform for AI\u2122\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/ja\\\/#organization\"},\"alternateName\":\"Couchbase, Inc.\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.couchbase.com\\\/ja\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"ja\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/ja\\\/#organization\",\"name\":\"Couchbase\",\"alternateName\":\"Couchbase, Inc.\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/ja\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ja\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/ja\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/Couchbase_Logo_Couchbase_Token_Red-1.png\",\"contentUrl\":\"https:\\\/\\\/www.couchbase.com\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/Couchbase_Logo_Couchbase_Token_Red-1.png\",\"width\":1129,\"height\":1129,\"caption\":\"Couchbase\"},\"image\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/ja\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/Couchbase\\\/\",\"https:\\\/\\\/x.com\\\/couchbase\",\"https:\\\/\\\/www.youtube.com\\\/c\\\/CouchbaseServer\",\"https:\\\/\\\/www.linkedin.com\\\/company\\\/couchbase\\\/\",\"https:\\\/\\\/github.com\\\/couchbase\\\/\",\"https:\\\/\\\/en.wikipedia.org\\\/wiki\\\/Couchbase,_Inc.\"],\"description\":\"Couchbase is a database software company headquartered in San Jose, California, providing an operational data platform for AI used by hundreds of global enterprises.\",\"legalName\":\"Couchbase, Inc.\",\"foundingDate\":\"2011-01-01\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Quickstart in Couchbase Lite Data Sync with iOS, Swift, and UIKit - Couchbase","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.couchbase.com\/ja\/developers\/tutorials\/quickstart-ios-uikit-sync\/","og_locale":"ja_JP","og_type":"article","og_title":"Quickstart in Couchbase Lite Data Sync with iOS, Swift, and UIKit","og_description":"Introduction Couchbase Sync Gateway is a key component of the Couchbase Mobile stack. It is an Internet-facing synchronization mechanism that securely syncs data across devices as well as between devices and the cloud. Couchbase Mobile uses a websocket based replication protocol. The core functions of the Sync Gateway include This tutorial will demonstrate how to &#8211; We will be using a Swift App as an example of a Couchbase Lite enabled client. You can learn more about the Sync Gateway here in the Sync Gateway Documentation. Prerequisites This tutorial assumes familiarity with building swift apps with Xcode and with Couchbase Lite. Note: If you are using an older version of [&hellip;]","og_url":"https:\/\/www.couchbase.com\/ja\/developers\/tutorials\/quickstart-ios-uikit-sync\/","og_site_name":"Couchbase","article_publisher":"https:\/\/www.facebook.com\/Couchbase\/","og_image":[{"width":2548,"height":1171,"url":"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/10\/Cloud-2.png","type":"image\/png"}],"twitter_card":"summary_large_image","twitter_site":"@couchbase","twitter_misc":{"Est. reading time":"30\u5206"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.couchbase.com\/ja\/developers\/tutorials\/quickstart-ios-uikit-sync\/","url":"https:\/\/www.couchbase.com\/ja\/developers\/tutorials\/quickstart-ios-uikit-sync\/","name":"Quickstart in Couchbase Lite Data Sync with iOS, Swift, and UIKit - Couchbase","isPartOf":{"@id":"https:\/\/www.couchbase.com\/ja\/#website"},"datePublished":"2023-08-28T13:56:25+00:00","breadcrumb":{"@id":"https:\/\/www.couchbase.com\/ja\/developers\/tutorials\/quickstart-ios-uikit-sync\/#breadcrumb"},"inLanguage":"ja","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.couchbase.com\/ja\/developers\/tutorials\/quickstart-ios-uikit-sync\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.couchbase.com\/ja\/developers\/tutorials\/quickstart-ios-uikit-sync\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.couchbase.com\/ko\/"},{"@type":"ListItem","position":2,"name":"Quickstart in Couchbase Lite Data Sync with iOS, Swift, and UIKit"}]},{"@type":"WebSite","@id":"https:\/\/www.couchbase.com\/ja\/#website","url":"https:\/\/www.couchbase.com\/ja\/","name":"Couchbase","description":"The Operational Data Platform for AI\u2122","publisher":{"@id":"https:\/\/www.couchbase.com\/ja\/#organization"},"alternateName":"Couchbase, Inc.","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.couchbase.com\/ja\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"ja"},{"@type":"Organization","@id":"https:\/\/www.couchbase.com\/ja\/#organization","name":"Couchbase","alternateName":"Couchbase, Inc.","url":"https:\/\/www.couchbase.com\/ja\/","logo":{"@type":"ImageObject","inLanguage":"ja","@id":"https:\/\/www.couchbase.com\/ja\/#\/schema\/logo\/image\/","url":"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/11\/Couchbase_Logo_Couchbase_Token_Red-1.png","contentUrl":"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/11\/Couchbase_Logo_Couchbase_Token_Red-1.png","width":1129,"height":1129,"caption":"Couchbase"},"image":{"@id":"https:\/\/www.couchbase.com\/ja\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/Couchbase\/","https:\/\/x.com\/couchbase","https:\/\/www.youtube.com\/c\/CouchbaseServer","https:\/\/www.linkedin.com\/company\/couchbase\/","https:\/\/github.com\/couchbase\/","https:\/\/en.wikipedia.org\/wiki\/Couchbase,_Inc."],"description":"Couchbase\u306f\u30ab\u30ea\u30d5\u30a9\u30eb\u30cb\u30a2\u5dde\u30b5\u30f3\u30ce\u30bc\u306b\u672c\u793e\u3092\u7f6e\u304f\u30c7\u30fc\u30bf\u30d9\u30fc\u30b9\u30bd\u30d5\u30c8\u30a6\u30a7\u30a2\u4f01\u696d\u3067\u3001\u6570\u767e\u306e\u30b0\u30ed\u30fc\u30d0\u30eb\u4f01\u696d\u304c\u4f7f\u7528\u3059\u308bAI\u7528\u306e\u904b\u7528\u30c7\u30fc\u30bf\u30d7\u30e9\u30c3\u30c8\u30d5\u30a9\u30fc\u30e0\u3092\u63d0\u4f9b\u3057\u3066\u3044\u307e\u3059\u3002.","legalName":"Couchbase, Inc.","foundingDate":"2011-01-01"}]}},"permalink_manager":null,"_links":{"self":[{"href":"https:\/\/www.couchbase.com\/ja\/wp-json\/wp\/v2\/tutorials\/10274","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.couchbase.com\/ja\/wp-json\/wp\/v2\/tutorials"}],"about":[{"href":"https:\/\/www.couchbase.com\/ja\/wp-json\/wp\/v2\/types\/tutorials"}],"version-history":[{"count":0,"href":"https:\/\/www.couchbase.com\/ja\/wp-json\/wp\/v2\/tutorials\/10274\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.couchbase.com\/ja\/wp-json\/wp\/v2\/media?parent=10274"}],"wp:term":[{"taxonomy":"tutorial-languages","embeddable":true,"href":"https:\/\/www.couchbase.com\/ja\/wp-json\/wp\/v2\/tutorial-languages?post=10274"},{"taxonomy":"tutorial-tags","embeddable":true,"href":"https:\/\/www.couchbase.com\/ja\/wp-json\/wp\/v2\/tutorial-tags?post=10274"},{"taxonomy":"tutorial-technologies","embeddable":true,"href":"https:\/\/www.couchbase.com\/ja\/wp-json\/wp\/v2\/tutorial-technologies?post=10274"},{"taxonomy":"tutorial-types","embeddable":true,"href":"https:\/\/www.couchbase.com\/ja\/wp-json\/wp\/v2\/tutorial-types?post=10274"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}