UIImageView不会在UICollectionViewCell中显示下载的图像

时间:2016-11-27 09:43:07

标签: ios swift asynchronous uicollectionview

我有一个应该显示照片的集合视图。

当我从Assets.xcassets显示临时图像时,一切正常,但是当我从互联网上下载图像时,它不会显示任何内容。

CollectionViewController.swift

class CollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    @IBOutlet var collectionView: UICollectionView!

    var currentCategory:PhotoCategory!

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return currentCategory.images.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GalleryItemCollectionViewCell", for: indexPath) as! GalleryItemCollectionViewCell

        cell.setGalleryItem(imageURL: currentCategory.images[indexPath.row].image)
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let picDimension = self.view.frame.size.width / 4.0
        return CGSize(width: picDimension, height: picDimension)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        let leftRightInset = self.view.frame.size.width / 20.0
        return UIEdgeInsetsMake(0, leftRightInset, 0, leftRightInset)
    }
}

GalleryItemCollectionViewCell.swift

class GalleryItemCollectionViewCell: UICollectionViewCell {
    @IBOutlet var itemImageView: UIImageView!

    func setGalleryItem(imageURL:String) {
        //itemImageView.image = #imageLiteral(resourceName: "tempImage2")
        let url = URL(string: imageURL)
        DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
            let data = try? Data(contentsOf: url!)
            DispatchQueue.main.async(execute: {
                if let imageData = data {
                    if let image = UIImage(data: imageData) {
                        print("We do have the image")
                        self.itemImageView = UIImageView(image: image)
                    }
                }
            });
        }
    }
}

我确实看到"我们确实有图像"在输出中,所以下载完成,数据是UIImage。

如果我取消注释该行:

//itemImageView.image = #imageLiteral(resourceName: "tempImage2")

并删除以下异步,一切正常。

当我在ViewController中使用下载代码显示普通的UiImageView时,它确实有效。

更新

我最终在项目中添加了UIImageView的扩展名:

extension UIImageView {
    func downloadedFrom(link:String, contentMode mode: UIViewContentMode) {
        guard
            let url = NSURL(string: link)
            else {return}
        contentMode = mode
        URLSession.shared.dataTask(with: url as URL, completionHandler: { (data, response, error) -> Void in
            guard
                let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
                let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
                let data = data, error == nil,
                let image = UIImage(data: data)
                else { return }
            DispatchQueue.main.async(execute: {
                self.image = image
            });
        }).resume()
    }
}

我在cellForItemAt中添加了这样的图片:

cell.itemImageView.downloadedFrom(link: cell.photo.image, contentMode: .scaleAspectFill)

1 个答案:

答案 0 :(得分:0)

if let image = UIImage(data: imageData) {
                    print("We do have the image")
                    self.itemImageView.image = image
                }

更改为

public synchronized void start(){
    if (running) return;
    running = true;
    //startThread(); (mistake)
    thread = new Thread(this);
    thread.start();
}