【问题标题】:Swift How to add array of strings to httpBodySwift如何将字符串数组添加到httpBody
【发布时间】:2022-01-12 08:30:04
【问题描述】:

通常我们使用字典作为参数,但要删除我使用的照片 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
    }
}

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

【问题讨论】:

    标签: arrays swift alamofire urlsession


    【解决方案1】:

    你可以这样做:

    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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-07-11
      • 2023-03-27
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多