如何在Swift 5中使用Alamofire 5在api中传递带有其他参数的配置文件图像

时间:2019-05-10 05:41:54

标签: json swift api alamofire multipartform-data

AF.request(urlString, method: .post, parameters: paramValue,encoding: URLEncoding.queryString, headers: ["accesstoken": "123456"]).responseJSON {
            response in

            switch response.result {
            case .success(let JSON):
                print("Login Response NSDictionary---->>",JSON as! NSDictionary)
                delegate?.didSuccess(result: JSON as! NSDictionary, withID: "login")

                break
            case .failure(let error):
                print("error----->>",error)
                delegate?.didError(result: error, withID: "login")
            }
        }

1 个答案:

答案 0 :(得分:0)

尝试一下。它解决了我的问题

class func uploadImage(_ strURL: String, parameters: [String: Any]?,image: UIImage?,keyImage : String, success:@escaping apiSuccess, failure:@escaping apiFailure) {
        print(parameters as Any)
        var UrlFinal = ""
        do
        {
            try UrlFinal = baseURL + strURL.asURL().absoluteString
        }
        catch{

        }
        Alamofire.upload(
            multipartFormData: { MultipartFormData in

                for (key, value) in (parameters)! {
                    print((key, value))
                    MultipartFormData.append((value as! String).data(using: String.Encoding.utf8)!, withName: key)
                }
                if image != nil{
                    guard let imageData = image!.jpegData(compressionQuality: 1) else { return }

                    MultipartFormData.append(imageData, withName: keyImage, fileName: "file1.jpeg", mimeType: "image/jpeg")
                }

        }, to: UrlFinal) { (result) in

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

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

                })
                upload.responseJSON { response in
                    if let res = response.result.value{
                        print(res)
                        Global.appDelegate.hideLoader()
                        success(res)
                    }else{

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