23

我们如何在 Alamofire 4.0 的上传功能中添加认证头?

下面是示例代码,但是我看不到向函数添加标头的方法。

Alamofire.upload(
    multipartFormData: { multipartFormData in
        multipartFormData.append(unicornImageURL, withName: "unicorn")
        multipartFormData.append(rainbowImageURL, withName: "rainbow")
    },
    to: "https://httpbin.org/post",
    encodingCompletion: { encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload.responseJSON { response in
                debugPrint(response)
            }
        case .failure(let encodingError):
            print(encodingError)
        }
    }
)

之前版本的alamofire支持直接添加header,新版本不支持。有任何想法吗?

4

1 回答 1

79

我得到了解决方案。

Alamofire.upload(multipartFormData:{ multipartFormData in
         multipartFormData.append(unicornImageURL, withName: "unicorn")
         multipartFormData.append(rainbowImageURL, withName: "rainbow")},
       usingThreshold:UInt64.init(),
       to:"https://httpbin.org/post",
       method:.post, 
       headers:["Authorization": "auth_token"], 
       encodingCompletion: { encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload.responseJSON { response in
                debugPrint(response)
            }
        case .failure(let encodingError):
            print(encodingError)
        }
    })

希望它会帮助你。

于 2016-09-22T06:51:08.683 回答