# Upload and download on iOS / macOS

> Connect to Bitiful S4 on iOS and macOS with URLSession and presigned URLs: Swift examples for uploads with progress, downloads, and error handling.

Do not embed an AccessKey in a mobile app; the installation package can be decompiled. The recommended approach is for the app to request a presigned URL from your server and then upload directly to S4. For how the server issues URLs, see the examples for [Node.js](https://docs.bitiful.com/en/developer/sdk/nodejs-demo/start-to-use.md), [Go](https://docs.bitiful.com/en/developer/sdk/golang-demo/start-to-use.md), [Java](https://docs.bitiful.com/en/developer/sdk/java-demo/start-to-use.md), and other languages, or use the Node.js server in the [browser example](https://docs.bitiful.com/en/developer/sdk/browser-demo/start-to-use.md) directly.

This way the app only makes plain HTTP requests and does not need to integrate the AWS SDK.

The examples use only the built-in URLSession. They require Swift 5.9 or later, with iOS 16 / macOS 13 as the minimum OS versions.

## Upload files

```swift title="S4.swift"
import Foundation

enum S4Error: Error {
    case http(status: Int, code: String?)
}

/// Upload a local file to the presigned URL and return the ETag
func upload(
    file: URL,
    to url: URL,
    contentType: String? = nil,
    onProgress: (@Sendable (Double) -> Void)? = nil
) async throws -> String? {
    var request = URLRequest(url: url)
    request.httpMethod = "PUT"
    // Set this only if Content-Type was specified when signing; it must match exactly
    if let contentType {
        request.setValue(contentType, forHTTPHeaderField: "Content-Type")
    }
    let delegate = ProgressDelegate(onProgress: onProgress)
    let (body, response) = try await URLSession.shared.upload(
        for: request, fromFile: file, delegate: delegate)
    try check(response, body)
    return (response as? HTTPURLResponse)?.value(forHTTPHeaderField: "ETag")
}

final class ProgressDelegate: NSObject, URLSessionTaskDelegate, Sendable {
    let onProgress: (@Sendable (Double) -> Void)?
    init(onProgress: (@Sendable (Double) -> Void)?) { self.onProgress = onProgress }

    func urlSession(
        _ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64,
        totalBytesSent: Int64, totalBytesExpectedToSend: Int64
    ) {
        guard totalBytesExpectedToSend > 0 else { return }
        onProgress?(Double(totalBytesSent) / Double(totalBytesExpectedToSend))
    }
}

/// For non-2xx responses, extract the error code from the XML
func check(_ response: URLResponse, _ body: Data) throws {
    guard let http = response as? HTTPURLResponse else { return }
    guard !(200..<300).contains(http.statusCode) else { return }
    let xml = String(decoding: body, as: UTF8.self)
    let code = xml.firstMatch(of: /<Code>(.*?)<\/Code>/).map { String($0.1) }
    throw S4Error.http(status: http.statusCode, code: code)
}
```

## Request a URL and upload

```swift title="S4.swift"
struct UploadTicket: Decodable {
    let key: String
    let url: URL
}

/// Request an upload URL from your server
func requestTicket(filename: String, size: Int) async throws -> UploadTicket {
    var request = URLRequest(url: URL(string: "https://api.example.com/upload/single")!)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    // Add your own login credentials here
    request.httpBody = try JSONSerialization.data(
        withJSONObject: ["filename": filename, "size": size])
    let (body, response) = try await URLSession.shared.data(for: request)
    try check(response, body)
    return try JSONDecoder().decode(UploadTicket.self, from: body)
}

func uploadPhoto(_ file: URL) async throws -> String {
    let size = try file.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0
    let ticket = try await requestTicket(filename: file.lastPathComponent, size: size)
    _ = try await upload(file: file, to: ticket.url) { progress in
        print("Uploaded \(Int(progress * 100))%")
    }
    return ticket.key
}
```

Usage example:

```swift title="Usage"
do {
    let key = try await uploadPhoto(fileURL)
    print("Upload complete", key)
} catch S4Error.http(let status, let code) {
    print("Upload failed", status, code ?? "")
} catch {
    print("Network error", error)
}
```

For uploads that must continue in the background, create the session with `URLSessionConfiguration.background(withIdentifier:)` and use `uploadTask(with:fromFile:)`. Background sessions can only upload from a file.

## Download files

```swift title="S4.swift"
/// Download to a local file
func download(from url: URL, to destination: URL) async throws {
    let (temp, response) = try await URLSession.shared.download(from: url)
    if let http = response as? HTTPURLResponse, http.statusCode != 200 {
        try check(response, Data(contentsOf: temp))
    }
    try? FileManager.default.removeItem(at: destination)
    try FileManager.default.moveItem(at: temp, to: destination)
}
```

Public files and files on a CDN do not need signing; you can load them directly with `AsyncImage` and similar. You can also add [CoreIX parameters](https://docs.bitiful.com/en/coreix/basic.md) to fetch thumbnails sized to the screen.

## FAQ

<details>
<summary>Upload returns 403 SignatureDoesNotMatch</summary>

- If `ContentType` was specified when signing, the upload must send the same value; if it was not, no value is required;
- If `ContentLength` was specified when signing, the file size must match;
- Do not encode the URL a second time.

</details>

<details>
<summary>Upload returns 403 AccessDenied</summary>

The URL has expired, or the sub-user that issued it has no write permission. The phone clock does not affect presigned URLs, but the server clock does.

</details>

<details>
<summary>How do I upload large files</summary>

Have your server create the multipart upload and issue a URL for each part. The app reads the file one segment at a time, PUTs each part, records each part's ETag, and finally the server completes the upload. The flow is the same as [browser multipart upload](https://docs.bitiful.com/en/developer/sdk/browser-demo/start-to-use.md).

</details>

<details>
<summary>Downloading an installer package (apk, ipa) returns 403</summary>

S4 direct connections cannot serve these two file types. Use a [CDN domain](https://docs.bitiful.com/en/cdn/intro.md) instead.

</details>

## Related documentation

[**Presigned URLs and extensions**](https://docs.bitiful.com/en/developer/s3/presigned-url.md)

Full reference for request limits, rate limits, Simul-Transfer, and other parameters.

[**Error codes and troubleshooting**](https://docs.bitiful.com/en/developer/s3/errors.md)

Checklists for 403, SignatureDoesNotMatch, and other issues.

[**S3 API compatibility**](https://docs.bitiful.com/en/developer/s3/compatibility.md)

Support status and differences for each operation.

[**Upload files securely from the client**](https://docs.bitiful.com/en/best-practice/web-uploads.md)

Recommended practices for direct uploads from browsers and apps.
