Swift 如何将字符串数组添加到 httpBody

Swift How to add array of strings to httpBody

通常我们使用字典作为参数,但删除我使用的照片 API 只需要数组中该图像的字符串名称。

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 将单个字符串添加到 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
    }
}

这很好,但不知道如何使这个主体成为单个字符串数组而不仅仅是字符串。

你可以这样做:

let bodyData = try? JSONSerialization.data(withJSONObject: yourArray)

其次是

let bodyString = String(data: body, encoding: .utf8)

有解包,还有do/catch要写,但你明白了。

这一行guard let data = body.data(using: .utf8) else { throw Errors.encodingProblem }可以用let data = Data(body.utf8)简化,不需要展开。

终于,既然你在做

Array 
-- JSONSerialization.data(withJSONObject: theArray) --> 
Data 
-- String(data: theData, encoding: .utf8) --> 
String 
-- Data(theString.utf8) --> 
Data

您可能想要重写您的对象,避免不必要的转换:

struct BodyStringEncoding: ParameterEncoding {

    private let body: Data

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

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

    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        guard var urlRequest = urlRequest.urlRequest else { throw Errors.emptyURLRequest }
        urlRequest.httpBody = self.body
        return urlRequest
    }
}