我正在尝试显示预取的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®ionCode=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
}
答案 0 :(得分:0)
您需要
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