0

I need to upload data to server and There's this function

uploadTask(with request: URLRequest, from bodyData: Data) -> URLSessionUploadTask

which alamofire uses with almost same signature

upload(_ data: Data, with urlRequest: URLRequestConvertible)

any idea how to add name as a key for the appended data?

I've seen this iOS - How to upload a video with uploadTask? adding file name in headers, I've checked apple docs for it and it stated nothing about it

Thanks a lot

Abdoelrhman
  • 906
  • 8
  • 17
  • What do you want to upload? Do you want to use multipart request or are you performing some uploading task like file upload to server? – Rajan Maheshwari Jun 02 '18 at 16:27

1 Answers1

0

Suppose you want to upload an image with key named as userImage, then you can use multipart feature of Alamofire. I have used SwiftyJSON here. You can modify as per your own requirement.

var parameters: [String:Any]?

//fill your parameters with data. Image is stored as Data and other values are string in this case.

Alamofire.upload(multipartFormData: { (multipartFormData:MultipartFormData) in
        for (key, value) in parameters! {
            if key == "userImage" {
                multipartFormData.append(
                    value as! Data,
                    withName: key,
                    fileName: "profileImage.jpg",
                    mimeType: "image/jpg"
                )
            } else {
                //multipartFormData
                multipartFormData.append((value as! String).data(using: .utf8)!, withName: key)
            }
        }
    }, usingThreshold: 1, to: "yourServiceURL", method: .post, headers: ["yourHeaderkey":"value"]) { (encodingResult:SessionManager.MultipartFormDataEncodingResult) in

        switch encodingResult {
        case .success(let upload, _, _):
            upload.responseJSON { response in
                if response.result.error != nil {
                    return
                }
                if let data = response.result.value {
                    let json = JSON(data)
                }
            }
            break

        case .failure(let encodingError):
            debugPrint(encodingError)
            break
      }
  }
Rajan Maheshwari
  • 14,465
  • 6
  • 64
  • 98