如何在Alamofire 4和Swift 3中设置方法,标题,参数

时间:2016-10-05 14:44:26

标签: ios swift3 alamofire

Alamofire的过去版本中,对于send方法,标头和参数我曾经这样做过:

Alamofire.request(.GET, URLRequest, headers:headers, parameters: parameters)

但版本4和swift 3不同。 如何设置方法,发送标题和放大器参数β

2 个答案:

答案 0 :(得分:2)

Alamofire github的迁移指南很好地解释了这一点。

看看这里:

// Alamofire 3
let parameters: [String: AnyObject] = ["foo": "bar"]

Alamofire.request(.GET, urlString, parameters: parameters, encoding: .JSON)
.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
    print("Bytes: \(bytesRead), Total Bytes: \(totalBytesRead), Total     Bytes Expected: \(totalBytesExpectedToRead)")
}
.validate { request, response in
    // Custom evaluation closure (no access to server data)
    return .success
}
.responseJSON { response in
    debugPrint(response)
}

// Alamofire 4
let parameters: Parameters = ["foo": "bar"]

Alamofire.request(urlString, method: .get, parameters: parameters, encoding: JSONEncoding.default)
.downloadProgress(queue: DispatchQueue.utility) { progress in
    print("Progress: \(progress.fractionCompleted)")
}
.validate { request, response, data in
    // Custom evaluation closure now includes data (allows you to parse data to dig out error messages if necessary)
    return .success
}
.responseJSON { response in
    debugPrint(response)
}

答案 1 :(得分:0)

迁移指南解释得很好,但示例中没有标题,只是为了避免混淆,下面我添加了一个GET请求添加它们的示例。

Alamofire.request(URL, method: .get, parameters: parameters, headers: headers)
    .validate { request, response, data in
        return .success
    }
    .responseJSON { response in
        switch response.result {
        case .success:
            // do something
            break
        case .failure(let error):
            // handle error
            break
        }
    }

我在here中找到了这些信息,如果您对请求中的标题有疑问,请在那里查看。