使用Alamofire上传图像时崩溃

时间:2017-10-12 07:13:02

标签: ios swift alamofire

这就是我尝试使用Alamofire从手机图库上传图片的方式......

func uploadTheImg() {
    var i = Int()
        i = 0
        for img in imageArray {
            let url = "http://myUrl…"
            let headers = [ "Content-Type":"application/x-www-form-urlencoded"]

        let imageData: Data = (UIImageJPEGRepresentation(img, 0.6) as Data?)!

        i = i+1
        let parameters: [String: Any]  =
            [
                "seller_id": “263”,
                "is_default": "1",
                "sequence": "\(i)", //This specifies the no.of images picked from the phone gallery
                "image": imageData // This is each of the image in the array.
                "access_token": “4c10c1f41e2cfddb146fd54e871890e2”,
        ]
        Alamofire.upload(multipartFormData: {(multipartFormData) in
            let filePath = NSURL(fileURLWithPath: url)

            multipartFormData.append(imageData, withName: "image", fileName: "\(Date().timeIntervalSince1970).jpeg", mimeType: "image/jpeg")

            for (key, value ) in parameters {
                print(key,value)
                multipartFormData.append(((value) as AnyObject).data(using: String.Encoding.nonLossyASCII.rawValue)!, withName: key)   //CRASHES HERE
            }
        }, to: url)
        { (result) in
            switch result {
            case .success(let upload, , ):

                upload.uploadProgress(closure: { (progress) in
                    UILabel().text = "\((progress.fractionCompleted * 100)) %"
                    print (progress.fractionCompleted * 100)
                })
                upload.responseJSON { response in

                    guard ((response.result.value) != nil) else{
                        print(response.result.error!.localizedDescription)
                        return
                    }
                }
            case .failure(let encodingError):
                print(encodingError)
                break
            }}}}

但在这一部分...... multipartFormData.append(((value) as AnyObject... for循环打印"seller_id","is_default","sequence","image"的键和值,然后突然崩溃而不打印访问令牌。不知道造成这次事故的原因......

感谢任何帮助。谢谢......

2 个答案:

答案 0 :(得分:0)

您尝试将multipartFormData.append(((value) as AnyObject).data(using: String.Encoding.nonLossyASCII.rawValue)!, withName: key)替换为multiData.append(value.data(using: .utf8)!, withName: key)。 希望它能帮到你

答案 1 :(得分:0)

你可以这样做

让imgData = UIImageJPEGRepresentation(图片!,0.5)!

        Alamofire.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(imgData, withName: "pictureData",fileName: "file.jpg", mimeType: "image/jpg")}