// 由於要更新tableview 的image...
這項回call會去更新 主畫面的 UI image...
所以會建議放在 main queue 裡面去執行
func downloadPoster(url:String, completionHandler:@escaping (Data) -> ()){
if let okurl = URL(string: url){
//let request = NSMutableURLRequest(url: okurl)
let task = URLSession.shared.dataTask(with: okurl, completionHandler: { (data, response,
error) in
if error != nil{
}else{
if let posterData = data{
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
completionHandler(posterData)
})
}
}
})
task.resume()
}
}
在 tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
call
downloadPoster(url: movieCell.poster!) { (data) in
cell.imageView?.image = UIImage(data: data)
}
利用 UIImage(data: data) 去把data 轉成 UIImage.. 去放在 cell.imageView?.image裏頭
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
// Configure the cell...
//cell.textLabel?.text = "電影\(indexPath.row+1)"
let movieCell = movies[indexPath.row]
cell.textLabel?.text = movieCell.title
cell.detailTextLabel?.text = movieCell.year
downloadPoster(url: movieCell.poster!) { (data) in
cell.imageView?.image = UIImage(data: data)
}
return cell
}
沒有留言:
張貼留言