Having issue uploading image using Alamofire and Swift 4

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-01 12:11:11

问题


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:


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.



来源:https://stackoverflow.com/questions/48902787/having-issue-uploading-image-using-alamofire-and-swift-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!