Show Maxres or High Thumbnails with YouTube API

I am 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 table view where I show them and does not have the maxres icon, the app crashes. I want to tell the API to use the maxres thumbnails if there is a maxres thumbnail for that video, but if it doesn't, just use tall. 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)

                    }

      

The API doesn't seem to even look for the maxres thumbnails. It only shows high, medium and default. Whenever I use playlistItems it shows maxres thumbnails. Hmmm ...

+3


source to share


2 answers


You should never expand web data implicitly. Always use ?

instead !

.

For a thumbnail, you should check if the maxres thumbnail exists, and if not available, use the default instead.



if let thumbnailUrl = (items as AnyObject).value(forKeyPath: "snippet.thumbnails.maxres.url") as? String ?? (items as AnyObject).value(forKeyPath: "snippet.thumbnails.default.url") as? String {
    videoObj.videoThumbnailUrl = thumbnailUrl
}

      

+1


source


I made this page to view thumbnails as their url is simple and no avi required. Only their video ID.
As for "wep" or "jpg", it doesn't matter. Just a specific platform.



You will need to decide if you really want a high resolution image, as the size will affect the load time. You will also need to resize the image to fit the thumbnails.

0


source







All Articles