标题

时间:2016-10-25 06:09:31

标签: ios swift3 alamofire

如何使用Alamofire v4上传我自己的标题? 在v3的情况下,我像下面的代码一样创建了自己的函数,但我不能用v4做同样的事情。

static func upload(method: Alamofire.Method, urlString: String, multipartFormData: (data: Alamofire.MultipartFormData) -> (), completionHandler: (
    response: Response<AnyObject, NSError>, statusCode:Int, json:JSON) -> ()){
        Alamofire.upload(method, urlString, headers: MyRequest.makeHeaders(), multipartFormData: multipartFormData, encodingCompletion: {
            encodingResult in
            switch encodingResult {
            case .Success(let upload, _, _):
                upload.responseJSON { response in
                    switch response.result {
                    case .Failure:
                        log.error("Upload request failed!!")
                    case .Success:
                        completionHandler(response: response, statusCode: (response.response?.statusCode)!, json:JSON(response.result.value!))
                    }
                }
            case .Failure(let error):
                log.warning((error as NSError).localizedDescription)
            }
        })
}

我尝试使用以下代码,但它不起作用

static func upload(_ method: Alamofire.HTTPMethod, urlString: String, multipartFormData: (Alamofire.MultipartFormData) -> Swift.Void, completionHandler: @escaping
    (_ response: NSDictionary, _ statusCode:Int, _ json:JSON) -> Void){

    Alamofire.upload(multipartFormData: multipartFormData, to: urlString, method: method, headers: MyRequest.makeHeaders(), encodingCompletion: {
        encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload.responseJSON { response in
                switch response.result {
                case .failure:
                    log.error("Upload request failed!!")
                case .success:
                    completionHandler(response: response, statusCode: (response.response?.statusCode)!, json:JSON(response.result.value!))
                }
            }
        case .failure(let error):
            log.warning((error as NSError).localizedDescription)
        }
    })

}

1 个答案:

答案 0 :(得分:2)

尝试以下代码:

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)
    }
})