Quickstart in Couchbase Lite with iOS, Swift, and UIKit

  • Learn how to install Couchbase Lite
  • Build an iOS App in Swift with UIKit and Couchbase Lite
  • Learn how to Create, Read, Update, and Delete documents

はじめに

Couchbase Mobile brings the power of NoSQL to the edge. It is comprised of three components:

  • Couchbase Lite (カウチベース・ライト), an embedded, NoSQL JSON Document Style database for your mobile apps
  • 同期ゲートウェイ, an internet-facing synchronization mechanism that securely syncs data between mobile clients and server, and
  • Couchbase Server, a highly scalable, distributed NoSQL database platform

Couchbase Mobile は柔軟なデプロイモデルをサポートしています。デプロイできるのは、

  • Couchbase Liteはモバイルアプリ内のスタンドアロンの組み込みデータベースとして、または,
  • Couchbase Lite は Sync Gateway を搭載したモバイルクライアントを有効にして、モバイルクライアント間のデータ同期を可能にします。あるいは、,
  • Couchbase Lite を搭載したクライアントは Sync Gateway を使用して、モバイルクライアントと Couchbase Server の間でデータを同期させることができます。これにより、データをクラウド (パブリックまたはプライベート) に保存できます。

このチュートリアルでは、どのように使用できるかの非常に基本的な例を説明します。 Couchbase Lite 3 in standalone mode within your Swift app. In this mode, Couchbase Lite will serve as a local, embedded data store within your iOS App and can be a replacement for SQLite or Core Data.

基礎を学ぶ

  • データベース操作
  • ドキュメントのCRUD操作

Couchbase Mobileについてもっと詳しく知ることができます。 これ.

前提条件

This tutorial assumes familiarity with building Swift apps with Xcode.

  • iOS (Xcode 12/13) Download latest version from the Mac App Store

注記他の開発ニーズのために保持する必要がある古いバージョンのXcodeを使用している場合は、既存のXcodeのコピーを作成し、最新のXcodeバージョンをインストールしてください。これにより、Mac上で複数のXcodeバージョンを持ち続けることができます。詳細については、こちらをご覧ください。 Appleの開発者向けドキュメント.

アプリの概要

非常にシンプルな方法で作業を行います。 ユーザープロフィール app. It does one thing – Allow a user to log in and create or update their user profile data.

The user profile data is persisted as a Document in the local Couchbase Lite Database. So, when the user logs out and logs back in again, the profile information is loaded from the Database.

App Overview Figure 1. The sample user profile application running in a simulator

インストール

  • GitHubからプロジェクトを複製するには、ターミナルで以下のコマンドを入力してください。
  git clone https://github.com/couchbase-examples/ios-swift-cblite-userprofile-standalone.git

Installing Couchbase Lite XCFramework

Next, we will download the Couchbase Lite 3.0 XCFramework.

The Couchbase Lite iOS XCFramework is distributed via SPM, CocoaPods, Carthage, or you can download the pre-built framework. See the Getting Started – Install documentation for more information.

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:

  cd /path/to/UserProfileDemo/src

  sh install_tutorial.sh

Now, let’s verify the installation.

試してみてください

  • 開く UserProfileDemo.xcodeproj project file, located at /path/to/UserProfileDemo/src
open UserProfileDemo.xcodeproj
  • Use Xcode to build and run the project using a simulator.

  • ログイン画面が表示されていることを確認してください。.

User Profile Login Screen Image

Figure 2. User Profile Login Screen Image

データモデル

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 日付 そして ブロブ データ型。必須ではありませんが、推奨される慣行として、 “「type」” 関連するドキュメントの命名空間として機能するプロパティ。.

「ユーザープロファイル」ドキュメント

このアプリは一つのドキュメントを扱います。 “「type」” 財産の所有者 “「ユーザー」”. ドキュメント ID の形式は “user::demo@example”.

Example 1. A user profile document example

{
    "type":"user",
    "name":"Jane Doe",
    "email":"jane.doe@earth.org",
    "address":"101 Main Street",
    "image":CBLBlob (image/jpg)
}
  • The special blob data type that is associated with the profile image – see: Working with Blob.

UserRecord

について “「ユーザー」” Document is encoded to a native struct named UserRecord as shown in Example 2.

Example 2. The encoding of a UserRecord to a native structure

let kUserRecordDocumentType = "user"
typealias ExtendedData = [[String:Any]]
struct UserRecord : CustomStringConvertible{
  let type = kUserRecordDocumentType
  var name:String?
  var email:String?
  var address:String?
  var imageData:Data?
  var extended:ExtendedData? 
  
    var description: String {
      return "name = (String(describing: name)), 
      email = (String(describing: email)), 
      address = (String(describing: address)), 
      imageData = (imageData?.debugDescription 
      ?? " ")"
    }
}

基本的なデータベース操作

In this section, we will do a code walk-through of the basic Database operations.

データベースの作成/開く

When a user logs in, we create an empty Couchbase Lite Database for the user if one does not exist.

  • 開く DatabaseManager.swift ファイルを選択して、 openOrCreateDatabaseForUser() 関数です。.
func openOrCreateDatabaseForUser(_ 
  user:String, 
  password:String, 
  handler:(_ error:Error?)->Void) {
  • 私たちは、 DatabaseConfiguration. This is an optional step. In our case, we would like to override the default path of the Database. Every user has their own instance of the Database that is located in a folder corresponding to the user.
var options = DatabaseConfiguration()
guard let defaultDBPath = _applicationSupportDirectory else {
  fatalError("Could not open Application Support Directory for app!")
  return
}
// Create a folder for the logged in user if one does not exist
let userFolderUrl = defaultDBPath.appendingPathComponent(user, 
                                                         isDirectory: true)
let userFolderPath = userFolderUrl.path
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: userFolderPath) {
  try fileManager.createDirectory(atPath: userFolderPath,
                                  withIntermediateDirectories: true,
                                  attributes: nil)
  
}
// Set the folder path for the CBLite DB
options.directory = userFolderPath
  • Then we create a local Couchbase Lite database named “「userprofile」” for the user. If a database already exists for the user, the existing version is returned.
_db = try Database(name: kDBName, config: options)

データベースの変更の聞き取り

You can be asynchornously notified of any change (add, delete, update) to the Database by registering a change listener with the Database. In our app, we are not doing anything special with the Database change notification other than logging the change. In a real world app, you would use this notification for instance, to update the UI.

  • 開く DatabaseManager.swift ファイルを選択して、 registerForDatabaseChanges() 関数です。.
fileprivate func registerForDatabaseChanges() {
  • We register a change listener with the database. This is an optional step. We track the ListenerToken as it is needed for removing the listener.
dbChangeListenerToken = db?.addChangeListener({ [weak self](change) in
  guard let self = self else {
      return
  }
  for docId in change.documentIDs   {
      if let docString = docId as? String {
          let doc = self._db?.document(withID: docString)
          if doc == nil {
              print("Document was deleted")
          }
          else {
              print("Document was added/updated")
          }
      }
  }
})

Close a Database

When a user logs out, we close the Couchbase Lite Database associated with the user and deregister any database change listeners

  • 開く DatabaseManager.swift ファイルを選択して、 closeDatabaseForCurrentUser() 関数です。.
func closeDatabaseForCurrentUser() -> Bool {
  • Closing the database is pretty straightforward
try db.close()

Deregistering for Database Changes

  • 開く DatabaseManager.swift ファイルを選択して、 deregisterForDatabaseChanges() 関数です。.
fileprivate func deregisterForDatabaseChanges() {
  • We stop listening to database changes by passing in the ListenerToken associated with the listener.
if let dbChangeListenerToken = self.dbChangeListenerToken {
    db?.removeChangeListener(withToken: dbChangeListenerToken)
}

試してみてください

  • The app should be running in the simulator
  • Log into the app with any email Id and password. Let’s use the values “demo@example.com“ そして “「パスワード」” for user Id and password fields respectively. If this is the first time that the user is signing in, a new Database will be created. If not, the user’s existing database will be opened.
  • Confirm that the console log output has a message similar to the one below. In my example, I am logging in with a user email Id of “demo@example.com“.
Will open/create DB  at path Will open/create DB  at path /Users/yourusername/Library/Developer/CoreSimulator/Devices/E4E62394-9940-4AF8-92FC-41E3C794B216/data/Containers/Data/Application/65EAD047-B29A-400C-803F-F799BAE99CBA/Library/Application Support/demo@example.com
  • The above log message indicates the location of the Database for the user on your Mac.
  • Open the folder in your Finder app from the log message and verify that a Database with name “「userprofile」” ユーザーのために存在している

User Profile Database Location

ドキュメント操作

Once an instance of the Couchbase Lite Database is created/opened for the specific user, we can perform basic Document functions on the Database. In this section, we will walkthrough the code that describes basic Document operations

ドキュメントの読み取り

ユーザーがログインすると、「あなたのプロフィール」画面が表示されます。ロードを要求するリクエストが送信されます。 「ユーザープロファイル」ドキュメント ユーザーにとって。ユーザーが初めてログインしたときには、何も表示されません。 ユーザープロフィール ユーザー用のドキュメントです。.

  • 開く UserPresenter.swift ファイルを選択して、 userProfileDocId definition. This document Id is constructed by prefixing the term “user::” to the email Id of the user.
lazy var userProfileDocId: String = {
  let userId = dbMgr.currentUserCredentials?.user
  return "user::(userId ?? "")"
}()    
  • In the UserPresenter.swift ファイルを見つけ、 fetchRecordForCurrentUser() 関数です。.
func fetchRecordForCurrentUser(handler:@escaping(_
records:UserRecord?, _ error:Error?)->Void) {
  • 指定されたドキュメントを取得しようとします。 userProfileDocId データベースから取得したものです。.
guard let db = dbMgr.db else {
  fatalError("db is not initialized at this point!")
}

var profile = UserRecord.init()
profile.email = self.dbMgr.currentUserCredentials?.user 
self.associatedView?.dataStartedLoading()

// fetch document corresponding to the user Id
if let doc = db.document(withID: self.userProfileDocId)  { 
  profile.email  =  doc.string(forKey: UserRecordDocumentKeys.email.rawValue)
  profile.address = doc.string(forKey:UserRecordDocumentKeys.address.rawValue)
  profile.name =  doc.string(forKey: UserRecordDocumentKeys.name.rawValue)
  profile.imageData = doc.blob(forKey:UserRecordDocumentKeys.image.rawValue)?.content
}

The code example above does the following:

  • のインスタンスを作成します UserRecord 物体
  • 設定する メール property of the UserRecord with the email Id of the logged in user. This value is not editable.
  • Fetch a 不変性 copy of the Document from the Database
  • If document exists and is fetched succesfully, we use appropriate type-getters to fetch the various members of the Document based on the property name. Specifically, note the support of the getBlob type を入力して、型が type のプロパティの値を取得します。 ブロブ

ドキュメントの作成/更新

A 「ユーザープロファイル」ドキュメント is created for the user when the user taps the “Done” button on the “Profile Screen”. The function below applies whether you are creating a document or updating an existing version

  • 開く UserPresenter.swift ファイルを選択して、 setRecordForCurrentUser() メソッド。.
func setRecordForCurrentUser( _ record:UserRecord?,
 handler:@escaping(_ error:Error?)->Void) {
  • 私たちは創造します 可変性 instance of the Document. By default, all APIs in Couchbase Lite deal with immutable objects, thereby making them スレッドセーフ by design. In order to mutate an object, you must explicitly get a mutable copy of the object. Use appropriate type-setters to set the various properties of the Document
mutableDoc.setString(record?.type, forKey: UserRecordDocumentKeys.type.rawValue)

if let email = record?.email {
  mutableDoc.setString(email, forKey: UserRecordDocumentKeys.email.rawValue)
}
if let address = record?.address {
  mutableDoc.setString(address, forKey: UserRecordDocumentKeys.address.rawValue)
}

if let name = record?.name {
  mutableDoc.setString(name, forKey: UserRecordDocumentKeys.name.rawValue)
}

if let imageData = record?.imageData {
  let blob = Blob.init(contentType: "image/jpeg", data: imageData)
  mutableDoc.setBlob(blob, forKey: UserRecordDocumentKeys.image.rawValue)
}
  • 具体的には、以下のサポートを留意してください。 setBlob type を入力して、型が type のプロパティの値を取得します。 ブロブ.

  • ドキュメントを保存する

do {
  // This will create a document if it does not exist and overrite it if it exists
  // Using default concurrency control policy of "writes always win"
  try? db.saveDocument(mutableDoc)
  handler(nil)
}
catch {
  handler(error)
}

ドキュメントの削除

We don’t delete a Document in this sample app. However, deletion of a document is pretty straightforward and this is how you would do it.

if let doc = db.document(withID: idOfDocToRemove) {
   try db.deleteDocument(doc)
}

試してみてください

  • 「試す」セクションで説明されている手順に従うべきでした。 データベースの作成/開く
  • Enter a “name” for the user in the Text Entry box and Tap “Done”
  • 「成功したプロファイルの更新」というアラートメッセージが表示されることを確認します。初めてプロファイルの画面を更新すると、ドキュメントが作成されます。.

User Profile Document Creation

  • Now tap on the “Tap!” button and select an image from the Photo Album. Tap “Done”. Image Selection

  • 「成功したプロファイルの更新」というアラートメッセージが表示されることを確認します。この時点でドキュメントが更新されます。.

  • 「ログオフ」をタップしてアプリからログアウトする

  • 以前に使用したユーザーのメールアドレスとパスワードでアプリに再度ログインしてください。私の例では、 “demo@example.com“ そして “「パスワード」”. なので、その認証情報で再度ログインします。.

  • [プロファイル画面が表示されていることを確認してください] 名前 そして 画像 以前に設定した値です。.

Log Off and Log Back On

さらに詳しく

このチュートリアルを完了していただきありがとうございます!

This tutorial walked you through a very basic example of how to get up and running with Couchbase Lite as a local-only, standalone embedded data store in your iOS app. If you want to learn more about Couchbase Mobile, check out the following links.

関連書籍

データベースの膨大なサイズを過去のものとしておく

スタックの追加ごとに新たな請求書が発生し、管理するものがさらに増えます。2分でどれだけの節約ができるかを試算してください。.