如何使用alamofire上传用户的图像和其他用户详细信息作为参数,我正在使用Alamofire(4.5.1)

时间:2017-09-28 04:18:08

标签: ios xcode swift3 alamofire

我已经尝试了以下代码,但它抛出了一个错误  " FAILURE:responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(错误域= NSCocoaErrorDomain代码= 3840"字符1周围的值无效。" UserInfo = {NSDebugDescription =字符1周围的值无效) 。}))"

let manager = Alamofire.SessionManager.default
            manager.session.configuration.timeoutIntervalForRequest = 60

            let data = UIImagePNGRepresentation(image)!

            let request =  manager.upload(multipartFormData:{ multipartFormData in
                multipartFormData.append(data, withName: "userImage", mimeType: "image/png")

                for (key, value) in params {
                    multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)


                }},

                                          usingThreshold:UInt64.init(),
                                          to:URL + "profile/update_profile",
                                          method:.post,
                                          headers: header,
                                          encodingCompletion: { encodingResult in
                                            switch encodingResult {
                                            case .success(let upload, _, _):

                                                debugPrint(upload)
                                                upload.responseJSON { response in
                                                    debugPrint(response)
                                                }
                                            case .failure(let encodingError):
                                                print(encodingError)
                                            }
            })

2 个答案:

答案 0 :(得分:0)

我在ServiceHendler.swift文件中创建以下方法

func uploadImageWithAlamofire(Parameters params : [String : AnyObject]?,ImageParameters imgparams :  [NSObject : AnyObject]?,VideoParameters vidoparam :  [NSObject : AnyObject]?,Action action : NSString, success: @escaping (AnyObject) -> Void, failure: @escaping (AnyObject) -> Void)
    {

        var base_url = "BASEURL"
        base_url.append("Profile/ProfilePhoto")
        let ACCESS_TOKEN =  UserDefaults.standard.value(forKey: "access_token")
        let ACCESS_TYPE =  UserDefaults.standard.value(forKey: "token_type")
        let Auth_Token : NSString = "\(ACCESS_TYPE as! String) \(ACCESS_TOKEN as! String)" as NSString

        let headers:[String:String] = [
            "Authorization": Auth_Token as String,
            "Content-Type": "application/json"
        ]

        Alamofire.upload(multipartFormData: { multipartFormData in
            if imgparams != nil{
                for (key, value) in imgparams! {
                    if let imageData = UIImageJPEGRepresentation(value as! UIImage, 0.7) {
                        multipartFormData.append(imageData, withName: key as! String, fileName: "FILENAME.png", mimeType: "image/png")
                    }
                }
            }
            if vidoparam != nil{
                for (key, value) in vidoparam! {
                    multipartFormData.append(value as! URL , withName: key as! String, fileName: "\(NSDate().timeIntervalSince1970 * 1000).mp4", mimeType: "application/octet-stream")
                }
            }
            if params != nil
            {
                 for (key, value) in params! {
                      multipartFormData.append((value as! String).data(using: .utf8)!, withName: key as! String)
                 }
            }
            }, to: base_url, method: .post, headers: headers,
                 encodingCompletion: { encodingResult in
                    switch encodingResult {
                    case .success(let upload, _, _):
                        upload.uploadProgress { progress in
                            print(progress.fractionCompleted)
                        }
                        upload.response { [weak self] response in
                            guard self != nil else {
                                return
                            }
                            let responseString = String(data: response.data!, encoding: String.Encoding.utf8)
                            DispatchQueue.main.async {
                                return success(responseString as AnyObject)
                            }


                        }
                    case .failure(let encodingError):
                        print("error:\(encodingError)")
                        return failure(encodingError as AnyObject)
                    }
        })

    }

像这样调用此方法也可以传递更多参数

let imgparam : NSMutableDictionary = NSMutableDictionary()
       imgparam.setValue(UserProfileImg.image == nil ? UIImage.init() : UserProfileImg.image!, forKey: "YOURWEBSERVICEPARAMKEY")
}

// create another NSMutableDictionary for your regular param like username , first name , bob , gender , amount , etc. same and just pass that param in parameter file 

 ServiceHendler.uploadImageWithAlamofire(Parameters: nil, ImageParameters: imgparam as [NSObject : AnyObject], VideoParameters: nil, Action: "", success: { (Success) in
            if let newdata : NSString = Success as? NSString{
                let data: Data? = newdata.data(using: String.Encoding.utf8.rawValue)
                let json: Any? = try? JSONSerialization.jsonObject(with: data!, options: [])

                let arraydata : NSDictionary = json as! NSDictionary
                print(arraydata)
                if let result :NSString = arraydata.value(forKey: "Result") as? NSString{
                    self.imagename = result

                }
                else{
                    AppUtilities.sharedInstance.hideLoader()
                    AppUtilities.sharedInstance.showAlert(title: "Error", msg: "Something might be wronge.")
                }

            }
        }) { (error) in
            print(error)
        }

答案 1 :(得分:0)

尝试使用此方法,您甚至可以创建一个用于设置参数的循环。 (斯威夫特2.x)

for (key, value) in params {
                multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key) }

上传方法

func hitServiceUploadFile(fileURL:NSURL, fileName:String, timeStamp:String, token: String)
{
    //Convert all parameters into Data format and send fileData as URL
    Alamofire.upload(
        .POST,
        URL + "profile/update_profile",
        multipartFormData: { multipartFormData in
            multipartFormData.appendBodyPart(fileURL: fileURL, name: "Filedata")
            multipartFormData.appendBodyPart(data: value1.dataUsingEncoding(NSUTF8StringEncoding)!, name: "Key1")
            multipartFormData.appendBodyPart(data: value2.dataUsingEncoding(NSUTF8StringEncoding)!, name: "Key2")
            multipartFormData.appendBodyPart(data: value3.dataUsingEncoding(NSUTF8StringEncoding)!, name: "Key3")
        },
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .Success(let upload, _, _):
                upload.responseString { response in

                         print(response)

                        }
                    }
                }
            case .Failure(_):
                self.hideIndicator()
            }
        }
    )
}