简体   繁体   English

使用Alamofire和Swift 4上传图片时出现问题

[英]Having issue uploading image using Alamofire and Swift 4

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. 从图库中选择图像后,我在imageview中设置图像。 Api response is this : Api响应是这样的:

response: FAILURE: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." 响应:FAILURE:错误域= NSURLErrorDomain代码= -1001“请求超时。” 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.} 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 =请求超时。}

I am using Swift 4, Xcode 9. Please let me know what I am doing wrong? 我正在使用Swift 4,Xcode 9.请让我知道我做错了什么?

Here is my working code for image upload with alamofire(swift 4) . 这是我使用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
        }


    }
}

AFAIK There should be three possibilities. AFAIK应该有三种可能性。

1) Image type may be mis-match(eg. extension should be acceptable with back-end). 1)图像类型可能不匹配(例如,扩展应该是可接受的后端)。

2) Image size matters. 2)图像尺寸很重要。

3) You need to send image with proper key_tag. 3)您需要使用正确的key_tag发送图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM