This post discusses how to use Couchbase Lite as an embedded database to share data between your iOS App and iOS App Extension. App Extensions implement a specific task or functionality that can be exposed to other apps on the device or to the Operating System. In this post, we will walk through an example of how a Today Extension can be used with a Couchbase Lite embedded database in standalone mode.
NOTE: We will be discussing Couchbase Mobile v1.4 which is the current production release. But everything we discuss here applies to the newer Developer Preview version 2.0 of Couchbase Mobile
배경
Apple supports many kinds of App Extensions , each of which enables functionality that is relevant to a particular subsystem on the device. In this post, we will discuss how Couchbase Lite can be used with a Today Extension. This type of extension, also known as a “Widget”, appears in the Today view of the Notification Center and allows users get quick updates. You can learn more about how App Extensions work in the Apple Developer documents.
I’ll assume you’re familiar with developing iOS Apps in Swift and have a basic understanding of integrating Couchbase Lite into your iOS App. This Getting Started guide is a great place to begin. If would like to read up more on Couchbase, refer to the resources at the end of this post.
카우치베이스 라이트
Couchbase Lite is an embedded database that runs on devices. It can be used in several deployment modes. It can be used as a standalone embedded database or it can be used in conjunction with a remote Sync Gateway that would allow it to sync data across devices. In this post, we will use Couchbase Lite in standalone deployment mode. In this post, we will not go over the details of integrating with Couchbase Lite. The 카우치베이스 라이트 시작하기 블로그에서 시작하기 좋은 곳입니다.
Demo App
- Download the Demo Xcode project from the 깃허브 리포지토리 . We will use this app as an example in the rest of the blog.
1 |
git 복제 git@github.com:카우치바스랩/카우치베이스-모바일-ios-앱-확장.git |
- 의 지침을 따르세요. README file to install and run the app
This is a simple Task List app that allows users to add, edit, delete tasks. A user can mark tasks as completed. A Today Extension is bundled with the app that shows the top 2 tasks right in your notification center without the need to open the app. The user can mark tasks as completed right from the notification center.
All tasks are stored in a local Couchbase Lite database. This implies that the Container app and the extension will both need access to the database.
App Architecture
App Extensions are not standalone apps. They are bundled within an App, referred to as a “컨테이너 앱”. Although App Extensions are bundled in the Container app, they run independent of the Container App in a separate process . App Extensions are launched by other apps that need the extension’s functionality. The App that launches the App Extension is referred to as the “호스트 앱“. The extension’s UI is displayed in the context of the Host App.
컨테이너 앱과 해당 확장 프로그램은 자체 샌드박스에서 실행되는 독립적인 프로세스이지만, 컨테이너 앱과 해당 확장 프로그램은 다음을 통해 데이터를 공유할 수 있습니다. 공유 컨테이너.
The Shared Container can be set up by registering a unique App Group and enabling it for for both the container app and the extension. You will learn about setting this up in the next section.
Configuring App Groups
Refer to the Apple Developer Docs to learn more about configuring App Groups in your iOS app
열기 CBLiteApp.xc작업공간 of the demo app project that you downloaded.
- Open the “Capabilities” tab of CBLiteApp Container App target . You should see the App Group group.com.example.CBLiteSharedData enabled.

Enabling App Group for App
- Open the “Capabilities” tab of CBLiteTaskExtension target. You should see the same App Group, group.com.example.CBLiteSharedData enabled.

Configuring App group in Extension
Enabling the App Group capabilities for a target adds it to the Entitlements files for the container app and it’s extension.
- In addition , you will have to add the App Groups feature to your App Id registered in the Apple Developer Portal.

Configuring App Group for App in Apple Developer Portal
앱 연습
Build and Run the App by choosing the App Target “CBLiteApp”. Now switch to the Today view of the Notification Center
- 아래와 같이 새 확장 프로그램 위젯을 오늘 보기에 추가합니다.
- Switch to the App and add couple of tasks tapping on the “+” button. Switch to the corresponding Today widget. You will notice that the tasks that you added are displayed in the widget.
- Mark a task as “Completed” by tapping on the task. Now switch back to the Container app. You will notice the completion status of the tasks is updated to correspond to actions taken from the Today widget.
- Similarly edits or delete a task in the Container app by swiping the task entry. Switch to the Today widget. You will see the updated task list.
- If your device supports 3D Touch, you can do a force touch on the app icon on home screen to reveal the Top Tasks extension right there from the icon and you can interact with it. Pretty cool !
- Finally, terminate the Container App. Switch to the Today Widget and update the Completed status of a task. Relaunch the app. The tasks will be listed with the updated status.
코드 연습
Tasks are stored in a local Couchbase Lite embedded database. This implies that both the container app and the Today Extension need access to the database. As discussed earlier, the way to share data between the container app and the extension is through the Shared Container. This implies that the Couchbase Lite database must be located in the Shared Container.
The code to enable this is straightforward.
열기 DatabaseManager.swift 파일을 만듭니다.
The DatabaseManager is a singleton class that handles basic database management functions.
- Locate 앱그룹컨테이너URL 함수
This function constructs the path to the shared container folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// 1. 공유 그룹 컨테이너의 URL 가져오기 let 파일 관리자 = FileManager.기본값 guard let groupURL = 파일 관리자 .containerURL(보안 애플리케이션 그룹 식별자: "group.com.example.CBLiteSharedData") else { 반환 nil } let 저장소 경로 = groupURL.앱딩패스 컴포넌트("CBLite") let storagePath = 저장소 경로.경로 // 2: Create a folder in the shared container location with name"CBLite" 만약 !파일 관리자.파일 존재(atPath: storagePath) { do { 시도 파일 관리자.createDirectory(atPath: storagePath, 와중간디렉토리: false, 속성: nil) } catch let 오류 { 인쇄("error creating filepath: \(오류)") 반환 nil } } 반환 저장소 경로 |
- 공유 그룹 컨테이너의 URL을 반환합니다. 그룹 컨테이너는 다음 위치에 저장됩니다. ~/Library/Group Containers/<application-group-id>
- 공유 그룹 컨테이너에 CBLite라는 폴더를 만듭니다.
- Locate configureCBManagerForSharedData 함수
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
do { // 카우치베이스 라이트 데이터베이스 폴더의 파일 보호 모드를 설정합니다. let 옵션 = CBLManagerOptions(읽기 전용: false, 파일 보호: 데이터.쓰기 옵션.completeFileProtectionUnlessOpen) let cblp옵션 = UnsafeMutablePointer<CBLManagerOptions>.할당(용량: 1) cblp옵션.초기화(에: 옵션) 만약 let URL = self.앱그룹컨테이너URL() { // 2. 공유 컨테이너의 디렉터리로 CBLManager를 초기화합니다. _cbManager = 시도 CBLManager.init(디렉토리: URL.상대 경로, 옵션: cblp옵션) } 반환 true } catch { 반환 false } |
- Create CBLManagerOptions options object with the appropriate file protections. A value of completeFileProtectionUnlessOpen 는 파일이 열려 있지 않으면 파일에 대한 읽기/쓰기 액세스가 제한됨을 의미합니다.
- Initialize the CBLManager with the path to the shared container. When the database is created, it will be created in the shared container.That’s it! The Couchbase Lite database is now in the Shared Container that both the App and the Extension can read and write to.
다음 단계는 무엇인가요?
Explore the rest of the demo sample code to understand how documents are added, edited and deleted. Specifically look at the TaskPresenter.swift file. This is where all the interactions with the Couchbase Lite database is handled.
If you have any questions, feel free to reach out to me on 트위터. 개선 사항을 제안하려면 풀 리퀘스트를 제출하세요. GitHub 리포지토리에 저장하세요. Couchbase Lite와의 통합에 대한 자세한 내용은 이 문서에서 확인할 수 있습니다. 카우치베이스 라이트 시작하기 blog. The 카우치베이스 포럼 는 질문을 게시할 수 있는 또 다른 좋은 장소입니다.
While this post discusses the use of Couchbase Lite in standalone mode, stay tuned for an upcoming post that will enhance the capability to include synchronization with the cloud.