首页 > 解决方案 > Alamofire 5 上传编码完成

问题描述

我正在使用 Swift 4 和 Alamofire 5,我上传了两张 multibart 照片,我想打印进度

 AF.upload(
        multipartFormData: { MultipartFormData in

            MultipartFormData.append(firstPic, withName: "first_pic", fileName: "image.jpeg", mimeType: "image/jpeg")
            MultipartFormData.append(secondPic, withName: "second_pic", fileName: "image.jpeg", mimeType: "image/jpeg")

    }, to: urlString, encodingCompletion: { encodingResult in
        switch encodingResult {
        case .Success(let upload, _, _):
            upload.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
                print(totalBytesRead)
            }
            upload.responseJSON { request, response, result in
                print(result)
            }
        case .Failure(let encodingError):
            print(encodingError)
        }
    })

这得到一个错误说

参数标签 '(multipartFormData:, to:, encodingCompletion:)' 不匹配任何可用的重载

图书馆更新了代码还是什么?

标签: swiftalamofire

解决方案


请根据您的需要进行修改

func upload(image: Data, to url: Alamofire.URLRequestConvertible, params: [String: Any]) {
    AF.upload(multipartFormData: { multiPart in
        for (key, value) in params {
            if let temp = value as? String {
                multiPart.append(temp.data(using: .utf8)!, withName: key)
            }
            if let temp = value as? Int {
                multiPart.append("\(temp)".data(using: .utf8)!, withName: key)
            }
            if let temp = value as? NSArray {
                temp.forEach({ element in
                    let keyObj = key + "[]"
                    if let string = element as? String {
                        multiPart.append(string.data(using: .utf8)!, withName: keyObj)
                    } else
                        if let num = element as? Int {
                            let value = "\(num)"
                            multiPart.append(value.data(using: .utf8)!, withName: keyObj)
                    }
                })
            }
        }
        multiPart.append(image, withName: "file", fileName: "file.png", mimeType: "image/png")
    }, with: url)
        .uploadProgress(queue: .main, closure: { progress in
            //Current upload progress of file 
            print("Upload Progress: \(progress.fractionCompleted)")
        })
        .responseJSON(completionHandler: { response in
            //Do what ever you want to do with response
                if let error = response.error {
                    print(error)
                }
                guard let data = response.value else {
                    return 
                }
                print(value)
        })
}

推荐阅读