【问题标题】:Show Maxres or High Thumbnails using YouTube API使用 YouTube API 显示 Maxres 或高缩略图
【发布时间】:2018-01-13 10:48:10
【问题描述】:

我正在使用 YouTube API 为我的 YouTube 频道创建一个应用。我的一些视频有一个 maxres 缩略图,但其中一些没有。如果视频出现在我正在显示它们的 tableview 中,并且没有 maxres 缩略图,则应用程序崩溃。如果该视频有 maxres 缩略图,我想告诉 API 使用 maxres 缩略图,但如果没有,则只使用高的缩略图。这是我的代码。

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)

                    }

似乎 API 甚至没有在寻找 maxres 缩略图。它只显示高、中和默认值。但是,每当我使用 playlistItems 时,它都会显示 maxres 缩略图。嗯……

【问题讨论】:

    标签: ios swift youtube youtube-api alamofire


    【解决方案1】:

    您应该绝不隐式解开基于网络的数据。始终使用? 而不是!

    对于缩略图,您应该检查是否存在 maxres 缩略图,如果不可用,请使用默认值。

    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
    }
    

    【讨论】:

    • 抱歉,这没用。我用您提供的代码替换了videoObj.videoThumbnailUrl = (items as AnyObject).value(forKeyPath: "snippet.thumbnails.maxres.url") as! String。它只是在具有 maxres 的视频上显示默认缩略图。 API似乎没有调用maxres。在终端中,它只显示 high、medium 和 default。不过,每当我使用 playlistItems 时,都有一个 maxres 选项。嗯……
    【解决方案2】:

    我创建这个页面是为了查看thumbnails,因为他们的 URL 很简单,不需要 api。只是他们的视频 ID。
    至于“wep”或“jpg”,都是一样的。只是平台特定的。

    您需要确定的是您是否真的需要高分辨率图像,因为尺寸会影响加载时间。您还需要调整图像大小以适合您的缩略图大小。

    【讨论】:

      猜你喜欢
      • 2018-10-15
      • 2016-05-06
      • 1970-01-01
      • 2015-01-18
      • 1970-01-01
      • 2023-03-27
      • 2023-03-07
      • 2015-07-05
      • 2011-03-25
      相关资源
      最近更新 更多