Swift 3 Alamofire multipart upload

后端 未结 4 584
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 12:21

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

The problem occurs when uploading multipartFormData:

A         


        
4条回答
  •  囚心锁ツ
    2020-12-13 13:08

    For Swift 3 and 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:

    // 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-Type header from you multipartFormData as it contains boundaries.

    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.

提交回复
热议问题