# 在 iOS / macOS 中上传与下载

> iOS、macOS 用 URLSession 和预签名 URL 连接缤纷云 S4：带进度上传、下载与错误处理的 Swift 示例。

移动应用不要内置 AccessKey，安装包可以被反编译。推荐做法是：App 向你的服务端申请预签名 URL，再直接上传到 S4。服务端怎么签发，见 [Node.js](https://docs.bitiful.com/developer/sdk/nodejs-demo/start-to-use.md)、[Go](https://docs.bitiful.com/developer/sdk/golang-demo/start-to-use.md)、[Java](https://docs.bitiful.com/developer/sdk/java-demo/start-to-use.md) 等语言的示例，或直接使用 [浏览器示例](https://docs.bitiful.com/developer/sdk/browser-demo/start-to-use.md) 里的 Node.js 服务。

这样 App 里只有普通的 HTTP 请求，不需要集成 AWS SDK。

示例只使用系统自带的 URLSession，需要 Swift 5.9 以上，系统最低 iOS 16、macOS 13。

## 上传文件

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

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

/// 上传本地文件到预签名链接，返回 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"
    // 只有签名时指定了 Content-Type 才需要设置，且必须完全一致
    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))
    }
}

/// 非 2xx 时，从 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)
}
```

## 申请链接并上传

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

/// 向你的服务端申请上传链接
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")
    // 在这里带上你自己的登录凭证
    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("已上传 \(Int(progress * 100))%")
    }
    return ticket.key
}
```

使用示例：

```swift title="使用"
do {
    let key = try await uploadPhoto(fileURL)
    print("上传完成", key)
} catch S4Error.http(let status, let code) {
    print("上传失败", status, code ?? "")
} catch {
    print("网络错误", error)
}
```

退到后台仍要继续的上传，请用 `URLSessionConfiguration.background(withIdentifier:)` 创建会话，并用 `uploadTask(with:fromFile:)`。后台会话只能从文件上传。

## 下载文件

```swift title="S4.swift"
/// 下载到本地文件
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)
}
```

公开文件或 CDN 上的文件不需要签名，可以直接用 `AsyncImage` 等加载，还可以加 [CoreIX 参数](https://docs.bitiful.com/coreix/basic.md) 按屏幕尺寸取缩略图。

## 常见问题

<details>
<summary>上传返回 403 SignatureDoesNotMatch</summary>

- 签名时指定了 `ContentType`，上传时必须发送相同的值；没有指定时不要求；
- 签名时指定了 `ContentLength`，文件大小必须一致；
- URL 不要再做一次编码。

</details>

<details>
<summary>上传返回 403 AccessDenied</summary>

链接过期，或签发链接的子账户没有写权限。手机时间不影响预签名链接，服务端时间会影响。

</details>

<details>
<summary>大文件怎么上传</summary>

由服务端创建分片上传并签发每一片的链接，App 读取文件的一段逐片 PUT，记下每片的 ETag，最后由服务端合并。流程与 [浏览器分片上传](https://docs.bitiful.com/developer/sdk/browser-demo/start-to-use.md) 相同。

</details>

<details>
<summary>安装包（apk、ipa）下载返回 403</summary>

S4 直连不能下载这两类文件，请用 [CDN 加速域名](https://docs.bitiful.com/cdn/intro.md)。

</details>

## 相关文档

[**预签名 URL 与扩展参数**](https://docs.bitiful.com/developer/s3/presigned-url.md)

限次、限速、同步传输等参数的完整说明。

[**错误码与排查**](https://docs.bitiful.com/developer/s3/errors.md)

403、SignatureDoesNotMatch 等问题的排查清单。

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

各操作的支持情况与差异。

[**在客户端中安全地上传文件**](https://docs.bitiful.com/best-practice/web-uploads.md)

浏览器与 App 直传的推荐做法。
