【问题标题】:AlamofireImage: How to downdload images with POST requestAlamofireImage:如何使用 POST 请求下载图像
【发布时间】:2018-05-10 14:20:39
【问题描述】:
一般来说,AlamofireImage 似乎应该使用 GET 方法请求。但是在我们的项目中,要下载图像,我们必须使用 POST 方法请求,因为我们发送访问令牌。我在 Stack Overflow 中搜索过类似的问题,但找不到足够的答案。有谁知道如何使用 POST 请求下载?
网址如下:
https://host_name/project_name/GetImage
【问题讨论】:
标签:
ios
swift
alamofire
urlrequest
alamofireimage
【解决方案1】:
您可以使用来自AlamofireImage 扩展的af_setImage 方法UIImageView 并传递任何URLRequestConvertible 参数。例如,使用 Alamofire 初始化器创建 URLRequest 实例:
let urlPath = "https://host_name/project_name/GetImage"
if var imageRequest = try? URLRequest(url: urlPath, method: .post) {
imageRequest.addValue("token", forHTTPHeaderField: "token_field")
imageView.af_setImage(withURLRequest: imageRequest)
}
【解决方案2】:
因为我们必须在 HTTPBodyData 中发送参数,所以按照 Loe 的回答,我对我们的代码进行了一些更改。以下是我们的新代码:
let urlPath = "https://host_name/project_name/GetImage"
let parameters:[String: Any] = [
"token": "tokenValue",
"imageName": "imageName"
]
let dataRequest = Alamofire.request(urlPath,
method: HTTPMethod.post,
parameters: parameters,
encoding: JSONEncoding.default,
headers: [:])
guard let imageRequest = dataRequest.request else {
return
}
imageView.af_setImage(withURLRequest: imageRequest)
重点是首先,我们创建一个DataRequestobject,然后用Alamofire.request()method将其转换为URLRequestType。