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&regionCode=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()
}
1

There are 1 best solutions below

0
On BEST ANSWER

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

let tempYTVideos = try JSONDecoder().decode(PopularVideos.self, from: data!)

Also, your data structures don't look right; There is no id property in the root object and there is no kid property in the item. An item has a kind and an id.

I would also suggest that you name your struct an Item rather than Items, since it represents a single item;

struct Item: Codable, Identifiable {
    
    let kind: String
    let id: String
}


struct PopularVideos: Codable {
    
    let kind : String
    let items : [Item]
}