Im new to swift, and im learning to parse data from Api to my Swift Apps. I tried to get data from Youtube APi of Popular video :(https://developers.google.com/youtube/v3/docs/videos/list) but I am not able to get the data, don't know where I am getting wrong. But its giving "Expected to decode Array but found a dictionary instead."
here is my model:
struct Items: Codable {
let kid : String
}
struct PopularVideos: Codable, Identifiable {
let id: String?
let kind : String
let items : [Items]
}
My Api request method:
//Getting Api calls for youtube video
func getYoutubeVideo(){
let url = URL(string: "https://www.googleapis.com/youtube/v3/videos?part=snippet&chart=mostPopular®ionCode=US&key=\(self.apiKey)")!
URLSession.shared.dataTask(with: url){(data, response, error) in
do {
let tempYTVideos = try JSONDecoder().decode([PopularVideos].self, from: data!)
print(tempYTVideos)
DispatchQueue.main.async {
self.YTVideosDetails = tempYTVideos
}
}
catch {
print("There was an error finding data \( error)")
}
} .resume()
}
The root object returned by that API call is not an array. It is a simple object that contains an array of
Item.So, you want
Also, your data structures don't look right; There is no
idproperty in the root object and there is nokidproperty in the item. An item has akindand anid.I would also suggest that you name your struct an
Itemrather thanItems, since it represents a single item;