1

我在通过 AlamofireImage 加载图像时遇到问题,如何在加载图像后更新单元格?或者我必须在 tableviewcell.swift 中提出请求

我的表视图控制器

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
    }
...
}
4

1 回答 1

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 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 的扩展

于 2016-09-13T08:21:25.773 回答