How to fix Alamofire responseJSON deprecated warning!!!! and how to use responseDecodable here

152 Views Asked by At

I am getting following warning on Xcode using Alamofire

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

Here is the code: this code is working but give above warning.

    let URL = "https://www.googleapis.com/youtube/v3/videos?id=\(videoId)&part=contentDetails&key=\(apiKey)"
    var duration = String()
    AF.request(URL).responseJSON { response in
        if let result = response.value as? [String : Any],
            let main = result["items"] as? [[String : Any]]{
            for obj in main{
                duration = (obj as NSDictionary).value(forKeyPath:"contentDetails.duration") as! String
                completionHandler(duration, nil)
                
            }
        }
    }

Any help with responseDecodable for the above will be greatly appreciated

1

There are 1 best solutions below

0
vadian On

According to your code the Codable structs are

struct YouTube: Decodable {
    let items: [Video]
}

struct Video: Decodable {
    let contentDetails: Detail
}

struct Detail: Decodable {
    let duration: String
}

Nowadays it's highly recommended to use the async/await API of Alamofire, and rather than calling the completion handler multiple times just return an array of strings

func loadDurations() async throws -> [String] {
    let url = "https://www.googleapis.com/youtube/v3/videos?id=\(videoId)&part=contentDetails&key=\(apiKey)"
    let response = try await AF.request(url).validate().serializingDecodable(YouTube.self).value
    return response.items.map(\.contentDetails.duration)
}

You have to wrap the function call in a Task and a do - catch block.