RileyDev
RileyDev

Reputation: 2515

How to use responseDecodable instead of responseJSON using Alamofire 6

One of my apps no longer works due to JSON serialisation failing when using Alamofire.

'responseJSON(queue:dataPreprocessor:emptyResponseCodes:emptyRequestMethods:options:completionHandler:)' is deprecated: responseJSON deprecated and will be removed in Alamofire 6. Use responseDecodable instead.

For code with the following lines

AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: [:]).responseJSON { response in.. } 

When changing to

AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: [:])
 .responseDecodable { response in... }

Then I get the error

Generic parameter 'T' could not be inferred

So I add the following

AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: [:])
  .responseDecodable(of: ResponseType.self) { response in.. } 

I get the error

Cannot find 'ResponseType' in scope

Does anyone have any suggestions?

Upvotes: 12

Views: 8735

Answers (2)

Scott
Scott

Reputation: 11

In Alamofire -> Documentation/Usage.md, I found the definition of the Decodable, so I try like this, then found working.

struct DecodableType: Decodable { 
    let url: String 
}

AF.request(urlString).responseDecodable(of: DecodableType.self) { response in
    switch response.result {
        case .success(let dTypes):
            print(dTypes.url)
        case .failure(let error):
            print(error)
    }
}

Upvotes: 1

vadian
vadian

Reputation: 285069

Unlike .responseJSON which returns a dictionary or array .responseDecodable deserializes the JSON into structs or classes.

You have to create an appropriate model which conforms to Decodable, in your code it's represented by ResponseType(.self).

The associated value of the success case is the root struct of the model.

But deprecated (in a yellow warning) means the API is still operational.

Side note: A JSON dictionary is never [String: Any?] the value is always non-optional.

Upvotes: 6

Related Questions