【问题标题】:Display youtube videos thumbnail and title inside UITableViewCell在 UITableViewCell 内显示 youtube 视频缩略图和标题
【发布时间】:2020-02-17 01:19:41
【问题描述】:

我正在尝试显示我预取的 YouTube 搜索结果。我的搜索功能会打印出标题、缩略图和视频 ID。我想在表格单元格中分配标题和缩略图。目标是最终在单击该视频的单元格时播放该视频。但现在我只想显示该表格单元格索引的相关信息。

    func search() {
    let videoType = "motivation"

    var dataArray = [[String: AnyObject]]()

    var apiKey = "xxxxx"
    var urlString = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=\(videoType)&type=video&videoSyndicated=true&chart=mostPopular&maxResults=10&safeSearch=strict&order=relevance&order=viewCount&type=video&relevanceLanguage=en&regionCode=GB&key=\(apiKey)"

    urlString = urlString.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)!
    let targetURL = URL(string: urlString)

    let config = URLSessionConfiguration.default // Session Configuration
    let session = URLSession(configuration: config)

    let task = session.dataTask(with: targetURL!) {

        data, response, error in
        if error != nil {
            print(error!.localizedDescription)

            return
        }

        else {
            do {
                typealias JSONObject = [String:AnyObject]

                let  json = try JSONSerialization.jsonObject(with: data!, options: []) as! JSONObject
                let items  = json["items"] as! Array<JSONObject>
                for i in 0 ..< items.count {

                    let snippetDictionary = items[i]["snippet"] as! JSONObject
                    print(snippetDictionary)
                    var youVideoDict = JSONObject()

                    youVideoDict["title"] = snippetDictionary["title"]
                    youVideoDict["channelTitle"] = snippetDictionary["channelTitle"]
                    youVideoDict["thumbnail"] = ((snippetDictionary["thumbnails"] as! JSONObject)["high"] as! JSONObject)["url"]
                    youVideoDict["videoID"] = (items[i]["id"] as! JSONObject)["videoId"]
                    dataArray.append(youVideoDict)

                    print(dataArray)
                }
            }

            catch {
                print("json error: \(error)")
            }

        }
    }
    task.resume() 
}

     override func viewDidLoad() {
    super.viewDidLoad()
    search()
    self.tableView.delegate = self
    self.tableView.dataSource = self
    tableView.register(YouTubeTableCell.self, forCellReuseIdentifier: cellID)
    view.addSubview(containerView)
    view.addSubview(titleLabel)
    containerView.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, paddingTop: 200, paddingLeft: 20, paddingBottom: 200, paddingRight: 20, width: 0, height: 0)

    containerView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    containerView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

    containerView.addSubview(tableView)
    tableView.translatesAutoresizingMaskIntoConstraints = false

    tableView.anchor(top: containerView.topAnchor, left: containerView.leftAnchor, bottom: containerView.bottomAnchor, right: containerView.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
    titleLabel.anchor(top: nil, left: nil, bottom: containerView.topAnchor, right: nil, paddingTop: 0, paddingLeft: 0, paddingBottom: 10, paddingRight: 0, width: 0, height: 0)
    titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

}
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 10
}


func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 140
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! YouTubeTableCell

    cell.titleLabel.text = "youtube video title"
    cell.thumbnail.image = 
    return cell
}

【问题讨论】:

    标签: ios swift youtube-api


    【解决方案1】:

    你需要

    1-

     dataArray.append(youVideoDict) 
     print(dataArray)
    }
    DispatchQueue.main.async {
       self.tableView.reloadData()
    }
    

    2-

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    

    3-

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! YouTubeTableCell
        let item = dataArray[indexPath.row]
        cell.titleLabel.text = item["title"] as! String
        let url = item["thumbnail"] as! String
        cell.thumbnail.sd_setImage(with:url), placeholderImage: UIImage(named: "placeholder.png")) 
        return cell
    }
    

    并安装SDWebImage

    提示:最好使用Codable 来解码模型的响应而不是JSONSerialization 和Dictionary

    【讨论】:

    • 感谢您的回复。这会一直返回一个空的 tableView。事实上,我的 tableView heightForRowAt 甚至都不起作用。你知道问题是什么吗?
    • 设置委托和数据源?
    • yes in viewDidLoad() 设置 self.tableView.delegate = self 和 self.tableView.datasource 相同。
    • 得到print("json error: \(error)") ?从viewDidLoad 拨打search ??
    • 我认为问题出在重新调整 dataArray.count 上,因为当我将其设置为返回 3 行时,高度和虚拟文本再次出现。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 2015-01-18
    • 1970-01-01
    • 2015-03-26
    • 2011-11-11
    • 2020-12-09
    • 2012-05-20
    相关资源
    最近更新 更多