ios Swift 3 Alamofire 分段上传

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39592085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 10:16:52  来源:igfitidea点击:

Swift 3 Alamofire multipart upload

iosswiftnetworkingalamofireswift3

提问by theDC

Thanks to migration to Swift 3, I find it difficult to compile my project that uses Alamofire.

由于迁移到 Swift 3,我发现很难编译使用 Alamofire 的项目。

The problem occurs when uploading multipartFormData:

上传multipartFormData时出现问题:

Alamofire.upload(.POST, URL, headers: headers, multipartFormData: {
        multipartFormData in
.
.
. 
}) 

Ambiguous reference to member 'upload(_:to:method:headers:)'

对成员 'upload(_:to:method:headers:)' 的不明确引用

Any help much appreciated, thanks in advance!

非常感谢任何帮助,提前致谢!

RESOLVED:

解决:

 Alamofire.upload(multipartFormData: { (multipartFormData) in

        multipartFormData.append(fileData, withName: "file_pack", fileName: "file_pack", mimeType: "text/plain")


        for (key, value) in self.parameters {
            multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
        }
        }, with: URL2, encodingCompletion: { (result) in

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

                upload.responseJSON { response in
                    self.delegate?.showSuccessAlert()
                    print(response.request)  // original URL request
                    print(response.response) // URL response
                    print(response.data)     // server data
                    print(response.result)   // result of response serialization
                    //                        self.showSuccesAlert()
                    self.removeImage("frame", fileExtension: "txt")
                    if let JSON = response.result.value {
                        print("JSON: \(JSON)")
                    }
                }

            case .failure(let encodingError):
                self.delegate?.showFailAlert()
                print(encodingError)
            }

    })

This is how upload method should be implemented in Swift 3

这是上传方法应该在 Swift 3 中实现的方式

采纳答案by pedrouan

For example, using Alamofire 4.0.0in Swift 3:

例如,在Swift 3 中使用Alamofire 4.0.0

(make sure you are 4.0.0 ready as it looks like you haven't updated your Alamofire yet)

(确保您已准备好 4.0.0,因为您似乎还没有更新您的 Alamofire)

Alamofire.upload(multipartFormData: { (multipartFormData) in
        // code
    }, to: URL, encodingCompletion: { (result) in
        // code
    })

or

或者

Alamofire.upload(multipartFormData: { (multipartFormData) in
        // code
    }, with: URL, encodingCompletion: { (result) in
        // code
    })

So headersneed to be passed by URL request:

所以headers需要通过 URL 请求传递:

let URL = try! URLRequest(url: "http://example.com", method: .get, headers: headers)

回答by Mitul Marsoniya

Try this one and url set as @pedrouansaid.

试试这个,并将 url 设置为@pedrouan所说的。

Alamofire.upload(multipartFormData: { (multipartFormData) in
       multipartFormData.append(imageData, withName: "xyz", fileName: "file.jpeg", mimeType: "image/jpeg")
}, to: url) 
{ (result) in
      //result
}

回答by Jorge Manuel Bello

In swift 3, trying to set multipartFormData as @DCDC pointed out in his solution. XCode try to cast to AnyObject before .data(), so instead of

在 swift 3 中,尝试将 multipartFormData 设置为@DCDC 在他的解决方案中指出的。XCode 尝试在 .data() 之前转换为 AnyObject,而不是

value.data(using: String.Encoding.utf8)!, withName: key

I did

我做了

[replace_your_var_name_here].data(using: String.Encoding.utf8)!, withName: key

In my case my var list was not big so hardcoding was an option.

就我而言,我的 var 列表并不大,因此可以选择硬编码。

回答by user1264176

For Swift 3 and Alamofire ~4.3.0

对于 Swift 3 和 Alamofire ~4.3.0

If someone like me tried to get request object synchronously (without using locks or dispatch_groups) you can use this approach:

如果像我这样的人尝试同步获取请求对象(不使用锁或 dispatch_groups),您可以使用这种方法:

// outer function
...
let string = "string to send"
let multipartFormData = MultipartFormData()
multipartFormData.append(string.data(using: .utf8)!, withName: "str")

guard let data = try? multipartFormData.encode() else {
    // fail appropriately
}

let request = sessionManager.upload(data,
                                    to: url,
                                    method: .post,
/* this is VERY IMPORTANT LINE */   headers: ["Content-Type" : multipartFormData.contentType])

request.validate()
// do whatever you need with request

Please note that you need to set Content-Typeheader from you multipartFormDataas it contains boundaries.

请注意,您需要设置Content-Type标题,multipartFormData因为它包含边界。

If you don't need to have your request object synchronously the other answer with

如果你不需要同步你的请求对象,另一个答案是

Alamofire.upload(multipartFormData: { (multipartFormData) in

is working as expected. In case of successful encoding of data it will return you request object in callback closure.

正在按预期工作。如果数据编码成功,它将在回调闭包中返回您的请求对象。

IMPORTANT NOTE:if you use the method I have described, it will block your thread (in most cases you probably are in Main thread) to copy and encode your data. So don't use it for large files or whatever. It is async in Alamofire on purpose.

重要提示:如果您使用我所描述的方法,它将阻止您的线程(在大多数情况下您可能在主线程中)复制和编码您的数据。所以不要将它用于大文件或其他任何东西。它在 Alamofire 中是异步的。