I am trying to upload image from gallery to server via my app. Here is my code :
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let userID:String = userDefaults.string(forKey: "userID"){
let URL: String = "HERE_IS_URL"
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
let imageData = UIImageJPEGRepresentation(chosenImage, 1.0)
dismiss(animated: true, completion: nil)
userProfilePicture.image = chosenImage
userProfilePicture.contentMode = .scaleToFill
let head: HTTPHeaders = [
"Content-type": "multipart/form-data",
"key": "key"
]
self.alamoManager?.upload(multipartFormData: { (multipartFormData) in
if let data = imageData{
multipartFormData.append(data, withName: "image", fileName: "image.png", mimeType: "image/png")
}
}, usingThreshold: UInt64.init(), to: URL, method: .get, headers: head) { (result) in
switch result{
case .success(let upload, _, _):
upload.responseJSON { response in
print("response: \(response)")
if let err = response.error{
print(err)
return
}
}
case .failure(let error):
print("Error in upload: \(error.localizedDescription)")
}
}
}
}
After selecting image from gallery , i set the image in imageview. Api response is this :
response: FAILURE: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x608000245760 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=MY_URL, NSErrorFailingURLKey=MY_URL, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.}
I am using Swift 4, Xcode 9. Please let me know what I am doing wrong?
Here is my working code for image upload with alamofire(swift 4)
.
func uploadImage(userImage : UIImage?,withCompletionHandler:@escaping (_ result: Any) -> Void){
Alamofire.upload(
multipartFormData: { MultipartFormData in
if((userImage) != nil){
MultipartFormData.append(UIImageJPEGRepresentation(userImage!, 0.025)!, withName: "your_tag", fileName: "imageNew.jpeg", mimeType: "image/jpeg")
}
}, to: "your_url_here") { (result) in
switch result {
case .success(let upload, _, _):
upload.responseJSON { response in
// getting success
}
case .failure(let encodingError): break
// getting error
}
}
}
A.F.A.I.K. There should be three possibilities.
1) Image type may be mis-match(eg. extension should be acceptable with back-end).
2) Image size matters.
3) You need to send image with proper key_tag.
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