Swift:图像缓存无法正常工作

时间:2016-06-07 11:18:59

标签: ios json swift

我试图解析此data source中的数据,正确解析并显示标题,但图像根本没有显示,也没有缓存。 下面是我的MyTableViewController.swift代码,其余类在这个问题中:Parsing image from iTunes using JSON to tableviewcontroller

class MyTableViewController: UITableViewController {
@IBOutlet var songsTable: UITableView!
let viewModel = ViewModel()
var imageCache = [String:UIImage]()
var songs = [NSManagedObject]()

override func viewDidLoad() {
    super.viewDidLoad()
    self.refresh()
    self.refreshControl = UIRefreshControl()
    self.refreshControl?.addTarget(self, action: #selector(MyTableViewController.refresh), forControlEvents: .ValueChanged)

}

func refresh() {
    viewModel.fetch {
        dispatch_async(dispatch_get_main_queue()) {
            self.tableView.reloadData()
            self.refreshControl?.endRefreshing()
        }
    }


}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return self.viewModel.numberOfSections()
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.viewModel.numberOfItemsInSection(section)
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! MyTableViewCell
    cell.songTitle.text = self.viewModel.titleForItemAtIndexPath(indexPath)
    //let song = songs[indexPath.row]
    //cell.songTitle.text = song.valueForKey("title") as? String


    let urlString = self.viewModel.imageForItemAtIndexPath(indexPath)

    let imgURL: NSURL = NSURL(string: urlString)!
    let request: NSURLRequest = NSURLRequest(URL: imgURL)
    NSURLConnection.sendAsynchronousRequest(
        request, queue: NSOperationQueue.mainQueue(),
        completionHandler: {(response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
            if error == nil {
                cell.songImage.image = UIImage(data: data!)
            }
    })

    let thumbnailURLString = self.viewModel.imageForItemAtIndexPath(indexPath)
    let thumbnailURL = NSURL(string: thumbnailURLString)!

    //if image is cached
    if let img = imageCache[thumbnailURLString] {
        cell.songImage?.image = img
        print("image is cached")
    }
    else {
        // The image isn't cached, download the img data
        // We should perform this in a background thread
        let request: NSURLRequest = NSURLRequest(URL: thumbnailURL)
        let mainQueue = NSOperationQueue.mainQueue()
        NSURLConnection.sendAsynchronousRequest(request, queue: mainQueue, completionHandler: { (response, data, error) -> Void in
            if error == nil {
                // Convert the downloaded data in to a UIImage object
                let image = UIImage(data: data!)
                // Store the image in to our cache
                self.imageCache[thumbnailURLString] = image
                // Update the cell
                dispatch_async(dispatch_get_main_queue(), {
                    if let cellToUpdate = tableView.cellForRowAtIndexPath(indexPath) as! MyTableViewCell?{
                        cellToUpdate.songImage?.image = image
                    }
                })
            }
            else {
                print("Error: \(error!.localizedDescription)")
            }
        })
    }

    return cell
}

感谢您花时间阅读本文。

1 个答案:

答案 0 :(得分:1)

您的代码令人困惑,但似乎有效。如果我将refresh函数更改为:

,我可以让它工作
func refresh() {
        viewModel.fetchTitles( {[unowned self] _ in
            self.viewModel.fetchImages({[unowned self] _ in
                dispatch_async(dispatch_get_main_queue()) {
                    self.tableView.reloadData()
                    self.refreshControl?.endRefreshing()
                }
            })
        }) 
    }

这是使用您在上一个问题中发布的代码。您可以尝试此操作或发布viewModel.fetch的代码。