I'm creating an app for my YouTube channel using the YouTube API. Some of my videos have a maxres thumbnail, but some of them don't. If a video appears in the tableview that I'm showing them in, and doesn't have a maxres thumbnail, the app crashes. I want to tell the API to use the maxres thumbnails if there are a maxres thumbnail for that video, but if there isn't, then just use the high one. This is my code.
Alamofire.request("https://www.googleapis.com/youtube/v3/search", parameters: ["part":"snippet","maxResults":50,"channelId":CHANNEL_ID,"playlistId":UPLOADS_PLAYLIST_ID,"q":searchText,"type":"video","key":API_KEY], encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
if let JSON = response.result.value {
if let dictionary = JSON as? [String: Any] {
var arrayOfVideos = [Video]()
guard let items = dictionary["items"] as? NSArray else { return }
for items in dictionary["items"] as! NSArray {
print("//Printing Video\n\(items)")
// Create video objects off of the JSON response
let videoObj = Video()
videoObj.videoID = (items as AnyObject).value(forKeyPath: "id.videoId") as! String
videoObj.videoTitle = (items as AnyObject).value(forKeyPath: "snippet.title") as! String
videoObj.videoDescription = (items as AnyObject).value(forKeyPath: "snippet.description") as! String
videoObj.videoThumbnailUrl = (items as AnyObject).value(forKeyPath: "snippet.thumbnails.maxres.url") as! String // Here I need to tell the API to use the maxres thumbnail if there is one.
arrayOfVideos.append(videoObj)
}
It seems like the API is not even looking for a maxres thumbnail. It only shows high, medium, and default. Whenever I use playlistItems, though, it does show the maxres thumbnails. Hmmmm...