Getting Started with iOS SDK

Welcome to Yorkie iOS SDK! In this guide, we will walk you through the steps to get started with the iOS SDK.

Using in your projects

Swift Package Manager

The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift compiler.

Once you have your Swift package set up, adding Yorkie as a dependency is as easy as adding it to the dependencies value of your Package.swift.

dependencies: [
.Package(url: "https://github.com/yorkie-team/yorkie-ios-sdk.git", from: "0.4.24")
]

How to use Yorkie

1. Creating a Client with API key

First, create a Client with API key

let client = Client("https://api.yorkie.dev"), ClientOptions(key: "xxxxxxxxxxxxxxxxxxxx"))
try await client.activate()

The API key is used to identify the project in Yorkie. You can get the API key of the project you created in the Dashboard.

2. Creating a Document

Then create a Document.

let doc = Document(key: docKey)
try await client.attach(doc, [:])

The document should be attached to the client in order to automatically synchronize it between the users participating the document.

3. Updating the Document

The created document is initially an empty object. You can create or update a key-value property you would like to share with peers using Document.update().

try await doc.update{ root, _ in
root.todos = Array<String>() // {"todos":[]}
(root.todos as? JSONArray)?.append("todo-1") // {"todos":["todo-1"]}
root.obj = ["name": "yorkie", "age": Int64(14)] // {"obj":{"name":"yorkie","age":14},"todos":["todo-1"]}
}

4. Accessing Document

If you want to access the document properties, you can use doc.getRoot(). Using a dot notation, you can access a key-value property you or your peers have set.

try await doc.update{ root, _ in
root.sharedMessage = "Hello World!"
}
await print(self.document.getRoot().sharedMessage!) // "Hello World!"

5. Subscribing to the changes that happen in the Document

Clients sharing the same document can subscribe to the changes that happen in the Document using doc.subscribe().

await doc.subscribe { event in
print("A change event occurred in the Document!")
}

You can execute different actions depending on the source of change. The source can be accessed from event.type.

The value can be: localChange, remoteChange or snapshot.

await doc.subscribe { event in
if event.type == .remoteChange {
print("A peer has changed the Document!")
}
}

6. Viewing the presence of users

You can also subscribe to the presence of users participating in the document using doc.subscribePresence(.presence). You can use doc.getPresences() to get the list of users who are currently involved in the document.

await doc.subscribePresnece { event in
// get all users connected to the Document.
let users = doc.getPresences() // [ (clientID: string, presence: [key: value]), ... ]
print("There are currently \(users.count) users online")
}

Next, let's take a look at the iOS SDK.