4
votes

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?

1
as i know you need identifier/ access param in multipart.dahiya_boy
any details about identifier/access param in multipart ? @dahiya_boyEA Rashel
Along file there must be some param that you have in your api.dahiya_boy
send multipart/form-data using POST method.Rocky
not worked . upload failed . but not get "The request timed out" error . simply api response with upload failed. @RockyEA Rashel

1 Answers

9
votes

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.