0

I need to check whether the image is nil or not which i assigned as one of the [key, value] pair in the dictionary. I need to send the dictionary as a parameter in Alamofire Post Method. But i couldn't pass the parameter. I will show what i have done. Clarify me what i did wrong! and give me the solution.

var parameters: [String : AnyObject ] = [
        "email" : "123@gmail.com",
        "password" : "password",
        "full_name": "XXX",
        "profile_pic" : UIImage(named: "abc")!
        ]
Alamofire.upload(
        .POST,
        "http://abc/public/user/register",
        multipartFormData: { multipartFormData in


            for (key, value) in parameters {

            multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
            }
        },
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .Success(let upload, _, _):
                upload.responseJSON { response in


                    debugPrint(response)

                }
            case .Failure(let encodingError):
                print(encodingError)
            }
        }
    )

I encounter an error says, unrecognized selector sent to an instance I would like to get the successful response back even if the profile_pic is nil or not. I get the success response if i append the image like this multipartFormData.appendBodyPart(fileURL: unicornImageURL, name: "unicorn").

The end result is that, the response should say that the user registration is successful even if he uploads the profile picture or not. Because it is an optional field right?!

Praveen Kumar
  • 298
  • 2
  • 15

2 Answers2

2

You can't set a key to nil in a collection like that. You need to check to see if it exists.

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

if let image = UIImage(named: "abc") {
  parameters["profile_pic"] = image
}
Dare
  • 2,497
  • 1
  • 12
  • 20
  • I tried this way but i get this error **AlamofirePostMethod[1234:123456] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIImage dataUsingEncoding:]: unrecognized selector sent to instance 0x7f84b24b8fc0'** – Praveen Kumar Apr 20 '16 at 14:26
0

After a while, I came across this answer. Hope this helps. Yes we can't set the value to nil in a collection as per Dare's answer. But we can skip the value if we don't want the value to be included in the parameter via optional chaining and type casting. Check out my answer here, how to pass a nil value for one of the parameter in alamofire Post request

Community
  • 1
  • 1
Praveen Kumar
  • 298
  • 2
  • 15