我有通过AlamofireImage加载图片的问题,如何在加载图片后更新单元格?或者我必须在tableviewcell.swift中提出请求
我的tableviewcontroller
class NewTableViewController: UITableViewController {
var videos = [Video](){
didSet {
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
}
let URL = "https://api.vid.me/channel/1/new"
override func viewDidLoad() {
super.viewDidLoad()
let request = Alamofire.request(.GET, self.URL)
request.responseObject { (response: Response<NewestVideos, NSError>) in
switch response.result {
case .Success(let newest):
self.videos = newest.videos!
print(self.videos)
case .Failure(let error):
print("Request failed with error: \(error)")
}
}
}
...
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! VideoTableViewCell
let video = videos[indexPath.row]
cell.titleLabel?.text = video.title != nil ? video.title! : "no name"
cell.videoImageView?.af_setImageWithURL(NSURL(fileURLWithPath: video.thumbnailUrl!)) //here i make image request from url (and url i get from request in viewdidload)
return cell
}
...
}
答案 0 :(得分:1)
您可以使用SDWebimage加载图像acsync,在加载完成后执行任何操作:
[self.imageView setImageWithURL:[NSURL URLWithString:imageURL]
placeholderImage:[UIImage imageNamed:@"YourPlaceholder.png"]
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
//... completion code here ...
}];
或者创建一个func来加载带有处理程序的图像,请看:
func imageForUrl(urlString: String, completionHandler:(image: UIImage?, url: String) -> ()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {()in
let downloadTask: NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: urlString)!, completionHandler: {(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
if (error != nil) {
completionHandler(image: nil, url: urlString)
return
}
if data != nil {
let image = UIImage(data: data!)
dispatch_async(dispatch_get_main_queue(), {() in
completionHandler(image: image, url: urlString)
})
return
}
})
downloadTask.resume()
})
}
并使用它:
yourimage.images = self.imageForUrl("link", completionHandler: { (image, url) in
// do s.t
})
你可以创建UIImage的扩展