我正在使用Alamofire在服务器上上传图像,这种方法效果很好,并且我已经在许多项目中使用过。

我使用以下代码使用多格式数据在服务器上上传图像。

Alamofire.upload( multipartFormData: { multipartFormData in

    for (key, value) in parameters {
        if let data = (value as! String).data(using: .utf8) {
            multipartFormData.append(data, withName: key)
        }
    }

    let imageData = image?.pngData()

    multipartFormData.append(imageData!, withName: "profile_image", fileName: "profileImage", mimeType: "")

}, to: getURL(.addProfile), headers: getHeaders(), encodingCompletion: { encodingResult in

    switch encodingResult {

    case .success(let upload, _, _):

        upload.response(completionHandler: { (defaultDataResponse) in

            guard let httpResponse = defaultDataResponse.response else {
                completion(nil, defaultDataResponse.error)
                return
            }

            if httpResponse.statusCode == 200 {

                do {

                    let genericModel = try JSONDecoder().decode(ProfileImageModel.self, from: defaultDataResponse.data!)
                    completion(genericModel, nil)

                } catch {

                    completion(nil, error)
                }

            } else {
                completion(nil, defaultDataResponse.error)
            }
        })

    case .failure(let encodingError):
        completion(nil, encodingError)
    }
})

这很好。

我的问题在这里,在api中传递了额外的参数。
for (key, value) in parameters {
    if let data = (value as! String).data(using: .utf8) {
        multipartFormData.append(data, withName: key)
    }
}

上面的代码会将字符串值转换为数据,并追加到multipartFormData。它适用于以下类型的请求结构。
{
    "first_name": "ABC",
    "last_name": "XYZ",
    "bio": "iOS Developer"
}

当我具有以下类型的请求结构时该怎么办?
{
    "first_name": "ABC",
    "last_name": "XYZ",
    "bio": "iOS Developer"
    "location": {
        "full_address": "My Location",
        "latitude": "23.0000",
        "longitude": "76.0000"
    }
}

请帮助实现这一目标。

最佳答案

使用这个功能

 func requestUploadImage(_ strURL : String, imageData : Data? ,params : [String : AnyObject]?, headers : [String : String]?, success:@escaping (NSDictionary) -> Void, failure:@escaping (Error) -> Void){
//        let  params = ["id": "101", "name": "Navin", "timezone": "2018-07-26  03:17:06" , "image": imageData] as [String : AnyObject]
  //
        //  CommonMethodsModel.showProgrssHUD()
    let url = URL(string: baseURL + strURL)!
    let parameters = params //Optional for extra parameter

        Alamofire.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(imageData!, withName: "image",fileName: "file.jpeg", mimeType: "image/jpeg")
            print(imageData , params)
            for (key, value) in parameters! {
                multipartFormData.append(value.data(using: String.Encoding.utf8.rawValue)!, withName: key)
            } //Optional for extra parameters
        },
                 usingThreshold: UInt64.init(),         to:url, method: .post)
        { (result) in
//             CommonMethodsModel.HidePrgressHUD()
            switch result {
            case .success(let upload, _, _):

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

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

                    success(response.result.value as! NSDictionary )
                }

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

    }

关于ios - 带有参数的Alamofire多功能上传图片,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55393342/

10-13 03:49