Skip to content
Console

Upload and download on iOS / macOS

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, Go, Java, and other languages, or use the Node.js server in the browser example 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

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

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:

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

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 to fetch thumbnails sized to the screen.

FAQ

Upload returns 403 SignatureDoesNotMatch
  • 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.
Upload returns 403 AccessDenied

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.

How do I upload large files

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.

Downloading an installer package (apk, ipa) returns 403

S4 direct connections cannot serve these two file types. Use a CDN domain instead.