0

I want to know why can't I give a file as one of the parameter values and to send the parameter as an upload request in Alamofire. I tried like this and it works.

let parameters: [String : AnyObject ] = [
        "email" : "abc@gmail.com",
        "password" : "password",
        "full_name": "XXX"]

let image: UIImage? = UIImage(named: "logo.png")

    Alamofire.upload(
        .POST,
        "http://myurl.com/register",
        multipartFormData: { multipartFormData in

            for (key, value) in parameters {
                multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
              }

                if let imageData = UIImageJPEGRepresentation(image!, 1) {
                multipartFormData.appendBodyPart(data: imageData, name: "profile_pic", fileName: "logo.png", mimeType: "image/png")
              }
       },
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .Success(let upload, _, _):
                upload.responseJSON { response in
                    debugPrint(response)
                }
            case .Failure(let encodingError):
                print(encodingError)
            }
        }
    )

Why can't I pass the image as a parameter value? And also why should I need to change the image in UIImageJPEGRepresentation.

If I pass the image as a value without changing the representation, error throws that it is not in NSData format.

Note that the request should pass even if there is an image or not, because it is an optional one.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Praveen Kumar
  • 298
  • 2
  • 15
  • What's the error you got when you tried with parameter? – zc246 Apr 22 '16 at 08:24
  • Says that `UIImage is not sent to an instance of type String` I need to store the value of the image in the parameter and to check the image available or not via optional chaining in the **for loop** itself. But here I'm checking the image is available or not, separately. Could you understand what I'm trying to convey?! – Praveen Kumar Apr 22 '16 at 11:30

1 Answers1

0

As you know, Alamofire just a library to help you to process a NSURLRequest. This is a common way that client can communicate with server via a HTTP request. Other platforms (such as Android, Desktop, or Web...) also use this way, too. So they must be same format. The post body only accepts simple data format such as String, Int, or byte[]... It does not know what is UIImage, but NSData. NSData is a format of byte[].

So, if you want to upload a text file, or a video, you have to convert it to NSData, too.

Hope this help.

t4nhpt
  • 5,264
  • 4
  • 34
  • 43