使用Alamofire和Swift 4上传图片时遇到问题 [英] Having issue uploading image using Alamofire and Swift 4

查看:169
本文介绍了使用Alamofire和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)")

            }
        }

     }

}

从图库中选择图像后,我在imageview中设置了图像。 Api响应是这样的:

After selecting image from gallery , i set the image in imageview. Api response is this :


响应:失败:错误Domain = NSURLErrorDomain代码= -1001请求超时。 UserInfo = {NSUnderlyingError = 0x608000245760 {Error Domain = kCFErrorDomainCFNetwork Code = -1001(null) UserInfo = {_ kCFStreamErrorCodeKey = -2102,_kCFStreamErrorDomainKey = 4}},NSErrorFailingURLStringKey = MY_URL,NSErrorFailingURLKey = MY_URL,_kCFStream ,NSLocalizedDescription =请求已超时。}

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.}

我正在使用Swift 4,Xcode9。请让我知道我在做什么错?

I am using Swift 4, Xcode 9. Please let me know what I am doing wrong?

推荐答案

这是我使用 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
应该有三种可能性。

A.F.A.I.K. There should be three possibilities.

1)图像类型可能不匹配(例如,后端应接受扩展名)。

1) Image type may be mis-match(eg. extension should be acceptable with back-end).

2)图像大小很重要。

2) Image size matters.

3)您需要发送带有适当key_tag的图像。

3) You need to send image with proper key_tag.

这篇关于使用Alamofire和Swift 4上传图片时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆