> ## Documentation Index
> Fetch the complete documentation index at: https://second.tech/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Get started with Swift

> Add Ark payments to your iOS or macOS application. Create a wallet, generate addresses, and check your balance in minutes.

Use this prompt to get started quickly.

# Bark SDK: Swift

Build Ark wallet apps for iOS and macOS with the `Bark` Swift package. Ark is a bitcoin layer 2 protocol for instant, low-fee, self-custodial payments.

## Prerequisites

* iOS 14+ or macOS 14+, with Xcode 15+ (Swift 5.9+)

## Install (Xcode)

File > Add Package Dependencies, enter `https://gitlab.com/ark-bitcoin/bark-ffi-bindings.git`, set the dependency rule to the exact version `0.25.0`, and add the `Bark` product to your app target.

## Install (Package.swift)

```swift theme={"theme":{"light":"github-light","dark":"github-dark"}}
platforms: [.iOS(.v14), .macOS(.v14)],
dependencies: [
    .package(url: "https://gitlab.com/ark-bitcoin/bark-ffi-bindings.git", exact: "0.25.0"),
],
// In your target's dependencies:
.product(name: "Bark", package: "bark-ffi-bindings")
```

## Create a wallet

```swift theme={"theme":{"light":"github-light","dark":"github-dark"}}
import Bark
import Foundation

// Store the wallet files in your app's Application Support folder
let appDir = try FileManager.default.url(
    for: .applicationSupportDirectory,
    in: .userDomainMask,
    appropriateFor: nil,
    create: true
).appendingPathComponent(Bundle.main.bundleIdentifier ?? "bark-quickstart")
try FileManager.default.createDirectory(at: appDir, withIntermediateDirectories: true)

// Signet tests only: don't store a real mnemonic in an unencrypted file
let mnemonicFile = appDir.appendingPathComponent("bark-mnemonic")
let mnemonic: String
if FileManager.default.fileExists(atPath: mnemonicFile.path) {
    mnemonic = try String(contentsOf: mnemonicFile, encoding: .utf8)
} else {
    mnemonic = try generateMnemonic()
    try mnemonic.write(to: mnemonicFile, atomically: true, encoding: .utf8)
}

// Configure the signet endpoints. nil leaves a setting at Bark's default.
let config = Config(
    serverAddress: "https://ark.signet.2nd.dev",
    serverAccessToken: nil,
    esploraAddress: "https://esplora.signet.2nd.dev",
    bitcoindAddress: nil,
    bitcoindCookiefile: nil,
    bitcoindUser: nil,
    bitcoindPass: nil,
    vtxoRefreshExpiryThreshold: nil,
    vtxoExitMargin: nil,
    htlcRecvClaimDelta: nil,
    fallbackFeeRate: nil,
    roundTxRequiredConfirmations: nil,
    daemonSyncIntervalSecs: nil,
    offboardRequiredConfirmations: nil,
    daemonManualSync: nil,
    lightningReceiveClaimRetries: nil,
    userAgent: nil,
    vtxoKeyGapLimit: nil
)

let datadir = appDir.appendingPathComponent("bark").path

// Create the wallet in datadir, or reopen it on later launches
let wallet = try await Wallet.open(
    network: .signet,
    mnemonicOrSeed: mnemonic,
    config: config,
    args: WalletOpenArgs(datadir: datadir, onchain: nil)
)
```

## Get address and check balance

```swift theme={"theme":{"light":"github-light","dark":"github-dark"}}
let address = try await wallet.newAddress()
print("Ark address: \(address)")
try await wallet.sync()
let balance = try await wallet.balance()
print("Spendable: \(balance.spendableSats) sats")
```

## Signet test environment

* Ark server: [https://ark.signet.2nd.dev](https://ark.signet.2nd.dev)
* Esplora API: [https://esplora.signet.2nd.dev](https://esplora.signet.2nd.dev)
* Faucet for test bitcoin: [https://signet.2nd.dev/](https://signet.2nd.dev/)
* Network enum: `Network.signet`

## Rules

* Open wallets with `Wallet.open(network:mnemonicOrSeed:config:args:)`. It creates the wallet on first launch and reopens it afterwards. There is no `Wallet.create()`.
* The `Config` initializer has no default values. Pass all 18 arguments in order, with `nil` for every setting you don't change.
* Set `serverAddress` and `esploraAddress` in `Config`. `Wallet.open()` fails without an Esplora URL. Leave the `bitcoind*` fields `nil`. This SDK supports Esplora only. The network is the first argument of `Wallet.open()`, not a `Config` field.
* Pass the data directory with `WalletOpenArgs(datadir: datadir, onchain: nil)`. `onchain` has no default value, so pass `nil`.
* `datadir` is a file system path (`URL.path`), not a `file://` URL. Bark creates the directory if it doesn't exist.
* Only one open wallet can use a `datadir` at a time, even within one process. A second `Wallet.open()` on it fails with "another process is already using datadir". Open the wallet once per process and reuse it.
* Reuse the same mnemonic on every launch. `Wallet.open()` fails with "incorrect mnemonic" if it doesn't match the wallet stored in `datadir`.
* `Wallet.open()`, `newAddress()`, `sync()`, and `balance()` are `async throws`. Call them with `try await` inside an `async throws` function or a `Task`. `generateMnemonic()` throws but isn't async, so call it with `try`.
* Balance amounts are `UInt64` values.
* In a sandboxed macOS app, add the `com.apple.security.network.client` entitlement (**App Sandbox** > **Outgoing Connections (Client)**). Without it, `Wallet.open()` fails with a DNS lookup error.
* Import `Bark` (capital B), not `bark`.
* Use `Network.signet` for testing. Mainnet is `Network.bitcoin`. Never use mainnet without user confirmation.
* Never hardcode or log mnemonics in production code.
* Correct terminology: Ark (not ARC), VTXO (not vtxo), on-chain (not onchain), off-chain (not offchain).
* "Bark" (capitalized) in prose, "bark" (lowercase) for CLI commands and repository names.

> [!TIP]
>
> These examples connect to **signet** so you can test for free. To go live, point the same configuration at Second's mainnet endpoints from [Connection details](https://second.tech/docs/connection-details.md) and select the mainnet network.

## Prerequisites

* iOS 14+ or macOS 14+, with Xcode 15+ (Swift 5.9+)

## Getting started

**1. Install the SDK**

> [tab] Xcode
>
> In Xcode, go to **File** > **Add Package Dependencies** and enter the package URL:
>
> ```
> https://gitlab.com/ark-bitcoin/bark-ffi-bindings.git
> ```
>
> For **Dependency Rule**, select **Exact Version** and enter `0.25.0`. Then add the `Bark` product to your app target.

> [tab] Package.swift
>
> Add the minimum platforms and the dependency to your `Package.swift`:
>
> ```swift theme={"theme":{"light":"github-light","dark":"github-dark"}}
> platforms: [.iOS(.v14), .macOS(.v14)],
> dependencies: [
>     .package(
>         url: "https://gitlab.com/ark-bitcoin/bark-ffi-bindings.git",
>         exact: "0.25.0"
>     )
> ]
> ```
>
> Then add the `Bark` product to your target's dependencies:
>
> ```swift theme={"theme":{"light":"github-light","dark":"github-dark"}}
> .target(
>     name: "YourApp",
>     dependencies: [
>         .product(name: "Bark", package: "bark-ffi-bindings")
>     ]
> )
> ```

In a macOS app, open your app target's **Signing & Capabilities** tab. Under **App Sandbox**, select **Outgoing Connections (Client)**.

**2. Create a wallet**

Generate a BIP39 mnemonic, configure the signet endpoints, and open the wallet in a data directory. `Wallet.open()` creates the wallet on the first launch and reopens it on later ones.

Run the code from this step and the next two inside an `async throws` function or a `Task`, with the `import` lines at the top of the file.

```swift theme={"theme":{"light":"github-light","dark":"github-dark"}}
import Bark
import Foundation

// Store the wallet files in your app's Application Support folder
let appDir = try FileManager.default.url(
    for: .applicationSupportDirectory,
    in: .userDomainMask,
    appropriateFor: nil,
    create: true
).appendingPathComponent(Bundle.main.bundleIdentifier ?? "bark-quickstart")
try FileManager.default.createDirectory(at: appDir, withIntermediateDirectories: true)

// Signet tests only: don't store a real mnemonic in an unencrypted file
let mnemonicFile = appDir.appendingPathComponent("bark-mnemonic")
let mnemonic: String
if FileManager.default.fileExists(atPath: mnemonicFile.path) {
    mnemonic = try String(contentsOf: mnemonicFile, encoding: .utf8)
} else {
    mnemonic = try generateMnemonic()
    try mnemonic.write(to: mnemonicFile, atomically: true, encoding: .utf8)
}

// Configure the signet endpoints. nil leaves a setting at Bark's default.
let config = Config(
    serverAddress: "https://ark.signet.2nd.dev",
    serverAccessToken: nil,
    esploraAddress: "https://esplora.signet.2nd.dev",
    bitcoindAddress: nil,
    bitcoindCookiefile: nil,
    bitcoindUser: nil,
    bitcoindPass: nil,
    vtxoRefreshExpiryThreshold: nil,
    vtxoExitMargin: nil,
    htlcRecvClaimDelta: nil,
    fallbackFeeRate: nil,
    roundTxRequiredConfirmations: nil,
    daemonSyncIntervalSecs: nil,
    offboardRequiredConfirmations: nil,
    daemonManualSync: nil,
    lightningReceiveClaimRetries: nil,
    userAgent: nil,
    vtxoKeyGapLimit: nil
)

let datadir = appDir.appendingPathComponent("bark").path

// Create the wallet in datadir, or reopen it on later launches
let wallet = try await Wallet.open(
    network: .signet,
    mnemonicOrSeed: mnemonic,
    config: config,
    args: WalletOpenArgs(datadir: datadir, onchain: nil)
)
```

> [!WARNING]
>
> The sample code stores the mnemonic in an unencrypted file so that the next launch reopens the same wallet. That is acceptable for signet tests only. In a production app, store the mnemonic in your platform's secure storage. Also set up [continuous wallet data backups](https://second.tech/docs/backups.md), so users can restore their wallet without the Ark server's cooperation.

**3. Get a receiving address**

Generate an Ark address to receive bitcoin.

```swift theme={"theme":{"light":"github-light","dark":"github-dark"}}
let address = try await wallet.newAddress()
print("Ark address: \(address)")
```

Run your app to print the address. In Xcode, `print()` output appears in the console. Send some signet sats to this address using [the faucet](https://signet.2nd.dev/).

**4. Check your balance**

Bark syncs the wallet in the background while it's open. Call `sync()` when you need an up-to-date balance right away.

```swift theme={"theme":{"light":"github-light","dark":"github-dark"}}
try await wallet.sync()

let balance = try await wallet.balance()
print("Spendable: \(balance.spendableSats) sats")
```

Balance amounts are `UInt64` values.

Run your app again. It reopens the same wallet and prints your spendable balance in sats.

## Next steps

> [card] [Source code](https://gitlab.com/ark-bitcoin/bark-ffi-bindings/-/tree/master/swift)
>
> Swift bindings source on GitLab.

> [card] [How Ark works](https://second.tech/docs/learn/intro.md)
>
> Learn about the protocol powering your wallet.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.