Home > OS >  Swift How to add array of strings to httpBody
Swift How to add array of strings to httpBody

Time:12-07

Normally we use dictionaries as parameters but to delete photo API that I work with needs just String name of that image in an array.

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"]

I got the method to add single String to httpBody with Alamofire:

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

And that's fine but don't know how to make this body to be single string array and not just string.

CodePudding user response:

You can do:

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

followed by

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

There is unwrapping, and do/catch to write, but you get the idea.

This line guard let data = body.data(using: .utf8) else { throw Errors.encodingProblem } can be simplified with let data = Data(body.utf8), no need to unwrap.

Finally, since you are doing

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

You might want to rewrite your object, avoiding unnecessary conversions:

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