0

I call the POST method like this

let parameters = ["empId": "1", "empName": "John"]
guard let url = URL(string: "test.com") else {
    return
}
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
do {
    urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch {

}
URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
    if let data = data, let response = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] {
        print(response)
    }
}.resume()

It works. Now I need to additionally send an image to server with type image/png with name image. How can I do that?

iOSDev
  • 326
  • 2
  • 10
  • I'm not sure exactly what you mean. If I read it correctly, you want to send the image to the server with `Content-Type image/png`, but you also wan't to supply a name? – Jacob King Oct 10 '19 at 07:16
  • @JacobKing I want to send the image to server with parameter name "image" – iOSDev Oct 10 '19 at 07:21
  • @JacobKing I tried `parameters["image"] = data`. I get `Invalid type in JSON write (Foundation.__NSSwiftData)` – iOSDev Oct 10 '19 at 07:22
  • So you can't serialise `Data` directly. You need to encode it in some way. If you're sending it in JSON, it's common to use Base 64.Try setting `parameters["image"] = data.base64EncodedString()`. – Jacob King Oct 10 '19 at 07:23
  • Also be aware that the server needs to expect Base 64. If you control the server code you can obviously facilitate this, else you should check the API docs and see what encoding it's expecting. – Jacob King Oct 10 '19 at 07:24
  • @JacobKing Unfortunately I dont have control to server code. And the API doc doesn't have any information regarding the encoding. In multipart can I send image in image/png format and other parameters in json? – iOSDev Oct 10 '19 at 07:30

2 Answers2

0

If you use Alamofire, ObjectMapper

These example is send image, string.


func requestMultipart<T: Mappable>(
  method: HTTPMethod,
  _ URLString: URLConvertible,
  parameters: [String: String]? = nil,
  images: [String: Data],
  encoding: Alamofire.ParameterEncoding = URLEncoding.default,
  success: @escaping (T) -> Void,
  failure: @escaping (Error) -> Void
) {
  Alamofire
    .SessionManager
    .default
    .upload(
      multipartFormData: { multipartFormData in
        if !images.isEmpty {
          images.forEach { (data) in
          multipartFormData.append(
            data.value,
            withName: data.key,
            fileName: data.key + ".jpeg",
            mimeType: "image/jpeg"
          )
        }
        parameters?.forEach { (params) in
          multipartFormData.append(
            params.value.data(
              using: String.Encoding.utf8,
              allowLossyConversion: false
            )!,
            withName: params.key
          )
        }
      },
      to: URLString,
      method: method,
      headers: header,
      encodingCompletion: { encodingResult in
        // handle
      }
    )
0

I am not sure how your backend reads your response, but usually backed services use multipart data

refer below link for multipart data: Upload image with parameters in Swift

yaswardhan
  • 11
  • 3