Getting Started for Apple
Published: 2021-10-27 13:23:52

###Introduction
Appwrite is a development platform providing you with easy yet powerful API and management console to get your next project up and running quickly.
This tutorial will help you start using Appwrite products and build your next project.
###Installation
Appwrite is a self-hosted backend server packaged as a set of Docker containers. You can install and run Appwrite on any operating system that can run a Docker CLI. You can use Appwrite on your local desktop or cloud provider of your choice.

####System Requirement:

Appwrite was designed to run well on both small and large deployment. The minimum requirements to run Appwrite is as little as 1 CPU core and 2GB of RAM, and an operating system that supports Docker.

####Install with Docker:

The easiest way to start running your Appwrite server is by running our Docker installer tool from your terminal. Before running the installation command, make sure you have Docker CLI installed on your host machine.

####Unix:

```bash
docker run -it --rm \
    --volume /var/run/docker.sock:/var/run/docker.sock \
    --volume "$(pwd)"/appwrite:/usr/src/code/appwrite:rw \
    --entrypoint="install" \
    appwrite/appwrite:0.11.0
```  

####Windows:

Hyper-V and Containers Windows features must be enabled to run Appwrite on Windows with Docker. If you don't have these features available, you can install Docker Toolbox that uses Virtualbox to run Appwrite on a Virtual Machine.

######CMD
```cmd
docker run -it --rm ^
    --volume //var/run/docker.sock:/var/run/docker.sock ^
    --volume "%cd%"/appwrite:/usr/src/code/appwrite:rw ^
    --entrypoint="install" ^
    appwrite/appwrite:0.11.0
```
######POWERSHELL
```powershell
docker run -it --rm ,
    --volume /var/run/docker.sock:/var/run/docker.sock ,
    --volume ${pwd}/appwrite:/usr/src/code/appwrite:rw ,
    --entrypoint="install" ,
    appwrite/appwrite:0.11.0
```
 
####Manual (using docker-compose.yml):

For advanced Docker users, the manual installation might seem more familiar. To setup Appwrite manually, download the Appwrite base docker-compose.yml and .env files. After the download completes, update the different environment variables as you wish in the .env file and start the Appwrite stack using the following Docker command:

```bash
docker-compose up -d --remove-orphans
```

Once the Docker installation completes, go to your machine hostname or IP address on your browser to access the Appwrite console. Please notice that on non-linux native hosts the server might take a few minutes to start after installation completes.

###Create Your First Appwrite Project
Go to your new Appwrite console, and once inside, click the icon '+' in the top navigation header or on the 'Create Project' button on your console homepage. Choose a name for your project and click create to get started.

###Add your Apple Platform
To init your SDK and start interacting with Appwrite services, you need to add a new Apple platform to your project. To add a new platform, go to your Appwrite console, choose the project you created in the step before, and click the 'Add Platform' button.

From the options, choose to add a new Apple platform, select the iOS, macOS, watchOS or tvOS tab and add your app name and bundle identifier, Your bundle identifier can be found at the top of the `General` tab in your project settings, or in your `Info.plist` file. By registering your new app platform, you are allowing your app to communicate with the Appwrite API.

###Get Appwrite Apple SDK
####Using Xcode
1. Select File > Swift Packages > Add Package Dependency
2.  Search for the Appwrite SDK with the URL https://github.com/appwrite/sdk-for-apple
3.  Add version rules
4.  Select next and wait for package resolution to complete
5.  Make sure `Appwrite` is selected to add to your target and select finish

####Using Swift Packages
Add this to your Package.swift file: 
```swift
'dependencies: [
    .package(url: "https://github.com/appwrite/sdk-for-apple", from: ""),
]')'
```
Then add the dependency to your target:
```swift
targets: [
    .target(
        name: "[YOUR_TARGET]",
        dependencies: [
            .product(name: "Appwrite", package: "sdk-for-apple")
        ]
    )
]
```

####OAuth Callback
In order to capture the Appwrite OAuth callback url, the following URL scheme needs to added to your `Info.plist`
```xml
<key>CFBundleURLTypes</key>
<array>
<dict>
    <key>CFBundleTypeRole</key>
    <string>Editor</string>
    <key>CFBundleURLName</key>
    <string>io.appwrite</string>
    <key>CFBundleURLSchemes</key>
    <array>
        <string>appwrite-callback-[PROJECT_ID]</string>
    </array>
</dict>
</array>

```
If you're using UIKit, you'll also need to add a hook to your `SceneDelegate.swift` file to ensure cookies work correctly.
```swift
targets: [
    func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
        guard let url = URLContexts.first?.url,
            url.absoluteString.contains("appwrite-callback") else {
            return
        }
        WebAuthComponent.handleIncomingCookie(from: url)
    }
]
```

###Init your SDK
Initialize your SDK code with your project ID, which can be found in your project settings page.  
```swift
import Appwrite

let client = Client()
  .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint
  .setProject("5df5acd0d48c2") // Your project ID
  .setSelfSigned() // For self signed certificates, only use for development
```
If you're using a physical device instead of a simulator, ensure that you can access your Appwrite instance before sending API calls.

When trying to connect to Appwrite from a physical device, localhost is the hostname for the device and not your local Appwrite instance. You should replace localhost with your private IP as the Appwrite endpoint's hostname. You can also use a service like ngrok to proxy the Appwrite API.

###Make Your First Request
Once your SDK object is set, access any of the Appwrite services and choose any request to send. Complete documentation for any service method you would like to use can be found in your SDK documentation or in the API References section. 
```swift
// Register User
let account = Account(client: client)
account.create(email: "email@example.com", password: "password") { result in
    switch result {
    case .failure(let error): print(error.message)
    case .success(let user): print(String(describing: user))
    }
}
```

###Listen to Changes
If you want to listen to changes in realtime from Appwrite, you can subscribe to a variety of channels and receive updates within milliseconds. Full documentation for Realtime can be found [here](https://appwrite.io/docs/realtime). 
```
// Subscribe to files channel
let realtime = Realtime(client: client)

let subscription = realtime.subscribe(channels: ["files"]) { message in
    if(message.event == "storage.files.create") {
        // Log when a new file is uploaded
        print(String(describing: message.payload))
    }
}
```
If you're using macOS, for realtime to function correctly you need to ensure you have both "Outgoing Connections (Client)" and "Incoming Connections (Server)" enabled in your App Sandbox settings in your project file.

###Full Example
```swift
import io.appwrite.Client
import Appwrite

let client = Client()
  .setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint
  .setProject("5df5acd0d48c2") // Your project ID
  .setSelfSigned() // For self signed certificates, only use for development

// Register User
let account = Account(client: client)
account.create(email: "email@example.com", password: "password") { result in
    switch result {
    case .failure(let error): print(error.message)
    case .success(let user): print(String(describing: user))
    }
}

// Subscribe to files channel
let realtime = Realtime(client: client)

let subscription = realtime.subscribe(channels: ["files"]) { message in
    if(message.event == "storage.files.create") {
        // Log when a new file is uploaded
        print(String(describing: message.payload))
    }
}
```

###Next Steps
Appwrite has many services and tools to help improve your app and speed up your development. The best way to learn how you can take advantage of them is to explore the different API references docs.