You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift如何使用Alamofire将字符串数组参数写入请求的httpBody

问题背景
  • 常规接口请求通常使用字典作为请求参数,但当前对接的删除照片API要求请求体仅传入包含图片URL字符串的数组
  • 示例请求头及请求体如下:
Content-Type: application/json; charset=UTF-8
Content-Length: 80
Authorization: Bearer [token]
["https://work-solution.s3.eu-north-1.amazonaws.com/job-83-image-gpfv7dfy.jpeg"]
现有实现

目前已经通过Alamofire实现了将单个String写入httpBody的方法,代码如下:

struct BodyStringEncoding: ParameterEncoding {

    private let body: String

    init(body: String) { self.body = body }

    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        guard var urlRequest = urlRequest.urlRequest else { throw Errors.emptyURLRequest }
        guard let data = body.data(using: .utf8) else { throw Errors.encodingProblem }
        urlRequest.httpBody = data
        return urlRequest
    }
}
需求

调整现有实现,让请求体为字符串数组而非纯字符串。

解决方案

有两种常用实现方式,按需选择即可:

方式一:修改Encoding实现,直接支持传入字符串数组(推荐,避免手动拼接JSON的转义错误)

struct BodyStringArrayEncoding: ParameterEncoding {
    private let stringArray: [String]

    init(stringArray: [String]) { self.stringArray = stringArray }

    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        guard var urlRequest = urlRequest.urlRequest else { throw Errors.emptyURLRequest }
        // 直接把数组序列化为JSON数据
        let data = try JSONSerialization.data(withJSONObject: stringArray, options: [])
        urlRequest.httpBody = data
        // 自动补全Content-Type,避免手动设置遗漏
        if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
            urlRequest.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
        }
        return urlRequest
    }
}

使用示例

let imageUrls = ["https://work-solution.s3.eu-north-1.amazonaws.com/job-83-image-gpfv7dfy.jpeg"]
AF.request(deleteUrl, method: .delete, encoding: BodyStringArrayEncoding(stringArray: imageUrls))
    .response { response in
    // 处理响应逻辑
}

方式二:不修改现有Encoding,手动把数组转成JSON字符串传入

如果你不想新增Encoding结构体,也可以直接把数组转成JSON字符串后复用现有BodyStringEncoding:

let imageUrls = ["https://work-solution.s3.eu-north-1.amazonaws.com/job-83-image-gpfv7dfy.jpeg"]
let jsonData = try JSONSerialization.data(withJSONObject: imageUrls, options: [])
let jsonString = String(data: jsonData, encoding: .utf8) ?? ""

AF.request(deleteUrl, method: .delete, encoding: BodyStringEncoding(body: jsonString))
    .response { response in
    // 处理响应逻辑
}

内容的提问来源于stack exchange,提问作者Lukasz D

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 20:45:01