Kazunori Takaishi
Kazunori Takaishi

Reputation: 2398

AlamofireImage: How to downdload images with POST request

AlamofireImage seems to be supposed to request with GET method in general. But in our project, to download images we have to request with POST method, because we send access token. I have searched for the similar question in Stack Overflow, but I couldn't find enough answers. Does anyone know how to download with POST request?

The URL is as follow:

https://host_name/project_name/GetImage

Upvotes: 1

Views: 796

Answers (2)

Kazunori Takaishi
Kazunori Takaishi

Reputation: 2398

Because We have to send parameters in HTTPBodyData, following the Loe's answer, I made some changes to our code. The following is our new code:

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)

The Point is first, we create a DataRequestobject and then convert it to URLRequest Type with Alamofire.request()method.

Upvotes: 1

Leo
Leo

Reputation: 3143

You can use af_setImage method from AlamofireImage extension of UIImageView and pass any URLRequestConvertible parameter. For example, create URLRequest instance with Alamofire initializer:

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

Upvotes: 1

Related Questions