Swift - HTTP加载失败(错误代码:-1005 [4:-4]),同时通过alamofire上传图像。

时间:2017-11-07 06:19:02

标签: ios swift alamofire

我是iOS的新手,使用Alamofire上传图片。我写的代码如下:

let image = imageView.image
        let imgData = UIImageJPEGRepresentation(image!, 0.2)!
        let headers: HTTPHeaders = [
            "x-access-token": "######",
            "Accept": "application/json"
        ]
        let parameters = ["profile_picture": "kinza"]
        let url = try! URLRequest(url: URL(string:"######")!, method: .post, headers: headers)

        Alamofire.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(imgData, withName: "profile_picture",fileName: "kinza.jpg", mimeType: "image/jpg")
            for (key, value) in parameters {
                multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            }
        },
                         with: url)
        { (result) in
            switch result {
            case .success(let upload, _, _):

                upload.uploadProgress(closure: { (progress) in
                    print("Upload Progress: \(progress.fractionCompleted)")
                })

                upload.responseJSON { response in
                    print(response.result.value)
                }

            case .failure(let encodingError):
                print(encodingError)
            }
        }

当我运行此代码时,我得到以下日志:

2017-11-07 11:03:21.595826+0500 TestApiProject[2457:51089] [] nw_socket_get_input_frames recvmsg(fd 6, 4096 bytes): [54] Connection reset by peer
2017-11-07 11:03:21.596094+0500 TestApiProject[2457:51089] TIC Read Status [1:0x6040003612c0]: 1:54
2017-11-07 11:03:21.596495+0500 TestApiProject[2457:51089] [] nw_socket_output_finished shutdown(6, SHUT_WR): [57] Socket is not connected
2017-11-07 11:03:21.597203+0500 TestApiProject[2457:51089] Task <9A25E63E-EC42-419C-A0B7-02998177EDCA>.<1> HTTP load failed (error code: -1005 [4:-4])
2017-11-07 11:03:21.597681+0500 TestApiProject[2457:51091] Task <9A25E63E-EC42-419C-A0B7-02998177EDCA>.<1> finished with error - code: -1005
Upload Progress: 1.0
nil

它已搜索但未找到任何特定于错误代码-1005&#39;我怎么解决呢?我错过了什么吗?

我对此有一些疑问:

  • 如果http加载失败,那么控制如何转到成功块 Alamofire请求?
  • response.result.value的值为零。我的错了 结束还是服务器端?
  • 我是否需要在info.plist中添加更多属性?这是怎么回事 现在是。

enter image description here

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

试试这个..

let image = imageView.image
        let imgData = UIImageJPEGRepresentation(image, 0.2)!

        let parameters = ["profile_picture": "kinza"]

        Alamofire.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(imgData, withName: "profile_picture",fileName: "kinza.jpg", mimeType: "image/jpg")
            for (key, value) in parameters {
                multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            }
        },to:"http://YOUR URL"){ (result) in

            switch result {
                case .success(let upload, _, _):

                    upload.uploadProgress(closure: { (progress) in
                        print("Upload Progress: \(progress.fractionCompleted)")
                    })

                    upload.responseJSON { response in
                        print(response.result.value!)
                    }

                case .failure(let encodingError):
                    print(encodingError)
            }
        }

这对我有用..

答案 1 :(得分:0)

您可以使用此方法,因为它对我有用:

fileprivate func p_uploadImage(_ image: UIImage) {

        let parameters = ["channelName" : "Your text param"]
        let fileData = UIImageJPEGRepresentation(image, 0.2)
        let URL2 = try! URLRequest(url: "Your URL", method: .post, headers: ["Authorization" : authKey!])

        Alamofire.upload(multipartFormData: { (multipartFormData) in

            multipartFormData.append(fileData!, withName: "upfile", fileName: "upfile", mimeType: "text/plain")


            for (key, value) in parameters {
                multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
            }
        }, with: URL2 , encodingCompletion: { (result) in

            switch result {
                case .success(let upload, _, _):
                    print("s")
                    upload.responseJSON {
                        response in
                        if let JSON = response.result.value as? [String : Any]{
                            let messageString = JSON["message"] as? String

                            }else {

                                let alertError = UIAlertController(title: "Alert", message: "Image upload error", preferredStyle: UIAlertControllerStyle.alert)
                                alertError.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
                                self.present(alertError, animated: true, completion: nil)
                            }

                        }
                    }
                case .failure(let encodingError):
                    print(encodingError)

                    let alertError = UIAlertController(title: "Alert", message: "Image upload error", preferredStyle: UIAlertControllerStyle.alert)
                    alertError.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
                    self.present(alertError, animated: true, completion: nil)
                }
            }
        )
    }