Having issues uploading images to my server from the iOS application I'm developing. I'm using Alamofire, and a UIImagePickerController
.
Inside the didFinishPickingMediaWithInfo
delegate method I'm saving the file the user selects as a NSURL
from info[UIImagePickerControllerReferenceURL]
in a variable named self.imageNSURL
.
Passing this along to Alamofires upload multipartFormData method as such (pretty much a standard copy and paste from their docs)
Alamofire.upload(
.POST,
URLString: "http://app.staging.acme.com/api/users/\(id)/picture",
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(fileURL: self.imageNSURL, name: "image")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { request, response, JSON, error in
println(JSON)
}
case .Failure(let encodingError):
println(encodingError)
}
}
)
The error in return I am getting is
Error Domain=com.alamofire.error Code=-1000 "The operation couldn’t be completed. The URL does not point to a file URL: assets-library://asset/asset.JPG?id=00000000-0000-0000-0000-000000000000&ext=JPG" UserInfo=0x00000000000 {NSLocalizedFailureReason=The URL does not point to a file URL: assets-library://asset/asset.JPG?id=00000000-0000-0000-0000-000000000000&ext=JPG}
Please note, I've nerfed the ID's in the response for this post, the actual error message contains valid ones.
Well this is due to the URL returned from info[UIImagePickerControllerReferenceURL]
this URL points to assets-library/asset, this due to sandboxing. So you cannot access the file using this URL thats why alamofire complains that your URL is not a file URL. To solve this problem you can use multipartFormData.appendBodyPart(data: data, name: name)
this method takes the data to be sent directly as NSData
. Full code example:
let imagePicked = info[UIImagePickerControllerOriginalImage]
let imageExtenstion = info[UIImagePickerControllerReferenceURL]
// imageExtenstion will be "asset.JPG"/"asset.JPEG"/"asset.PNG"
// so we have to remove the asset. part
var imagePickedData : NSData
switch imageExtenstion {
case "PNG": imagePickedData = UIImagePNGRepresentation(imagePicked)!
// compressionQuality is a float between 0.0 and 1.0 with 0.0 being most compressed with lower quality and 1.0 least compressed with higher quality
case "JPG", "JPEG": imagePickedData = UIImageJPEGRepresentation(image, compressionQuality)!
}
Alamofire.upload(.POST, YOUR_URL, multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: imagePickedData, name: imageName)
}, encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { request, response, JSON, error in
print(JSON)
}
case .Failure(let encodingError):
print(encodingError)
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With