Reputation: 3285
I'm trying to upload an image to server with some details, but I'm keep on receiving parameter missing error from the server. This is my image upload code
func uploadImages(imageData: NSData, withParams requestDict:NSDictionary, callBack:(responseDict: NSDictionary?, error: NSError?) -> ())
{
print(requestDict)
let boundary = generateBoundaryString()
let url:NSURL = NSURL(string: String(format: "%@%@", BASE_URL, IMAGE_UPLOAD_API))!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.timeoutInterval = FLOAT_CONSTANT_60
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.HTTPBody = createBodyWithParameters(requestDict as? [String : String], filePathKey: "image", imageData: imageData, boundary: boundary)
print(requestDict)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) in
do {
let JSON = try! NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.AllowFragments)
guard let JSONDictionary :NSDictionary = JSON as? NSDictionary else {
print("Not a Dictionary")
//get your JSONData here from dictionary.
return
}
callBack(responseDict: JSON as? NSDictionary, error: nil)
print("JSONDictionary! \(JSONDictionary)")
}
catch let JSONError as NSError {
print("\(JSONError)")
callBack(responseDict: nil, error: JSONError)
}
})
}
func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageData: NSData, boundary: String) -> NSData {
let body = NSMutableData()
if parameters != nil {
for (key, value) in parameters! {
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
let filename = "MyImage.jpg"
let mimetype = "image/jpg"
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimetype)\r\n\r\n")
body.appendData(imageData)
body.appendString("\r\n")
body.appendString("--\(boundary)--\r\n")
return body
}
/// Create boundary string for multipart/form-data request
func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().UUIDString)"
}
This is my server api format
"{
'deviceId' : 1234567,
'role' : 'admin',
'authToken' : 'cf01ebcd5844fde166940b06fbb267ba',
'userId' : 90490,
'appointmentId': 25067187,
'position' : 2,
'image' : ''
}"
And this is what the print response prints in the uploadImages method
{
appointmentId = 25067187;
authToken = b72e4d89aa53399dd3a04f1440dec704;
deviceId = "4DF3R180-55XC-4G3C-90F8-3431537ECCAF";
position = 2;
role = admin;
userId = 90490;
}
I believe the image parameter is the filePathKey string and gets attached in the request but I'm not able to print it to see the request after attaching the image. Is there something I'm doing wrong due to which the image parameter is not getting added?
This is how I call the method
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
dispatch_async(dispatch_get_main_queue(),{
let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage
let imageData = UIImageJPEGRepresentation(selectedImage!, 1)
let apiHandler = APIHandler()
apiHandler.uploadImages(imageData!, withParams: self.createImageUploadDict(), callBack: { (responseDict, error) -> () in
print(responseDict)
})
})
self.dismissViewControllerAnimated(true, completion: nil)
}
Upvotes: 0
Views: 663
Reputation: 3285
I figured out the issue, there was nothing wrong with the code, while creating the request dictionary I was actually using [String: AnyObject] but here I used [String:String] so thats why I got the parameter missing error.
Upvotes: 0