我的tableView滚动每次到达新单元格时都会冻结,并且必须加载图像

时间:2017-03-23 19:13:07

标签: swift xcode uitableview asynchronous uiimage

我有一个tableView,它有一个imageView作为背景,其中的图像可以在文档目录,NSCache中找到,或者如果在设备上找不到,则从Firebase下载。从Firebase下载时没有冻结,但是当单元格从设备加载图像时,滚动会冻结,直到它将图像作为背景图像加载。我无法弄清楚原因。下面是代码:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? TripCell

    let trip = trips[indexPath.row]

    let path = getDocumentsDirectory().appendingPathComponent(trip.coverUID)
    if var image = UIImage(contentsOfFile: path) {
        image = image.resizedImage(newSize: CGSize(width: (image.size.width)/2, height: (image.size.height)/2))
        cell?.updateUI(trip: trip, image: image)
        print("Loaded from DocumentsDirectory")
    } else if let data = TripsVC.imageCache.object(forKey: trip.coverUID as NSString) {
//This is mainly where it freezes
        var cachedImage = UIImage(data: data as Data)
        cachedImage = cachedImage?.resizedImage(newSize: CGSize(width: (cachedImage?.size.width)!/1.5, height: (cachedImage?.size.height)!/1.5))
        cell?.updateUI(trip: trip, image: cachedImage)
    } else {
        cell?.updateUI(trip: trip)
    }

    return cell!
}

func updateUI(trip: Trip, image: UIImage? = nil) {

    self.trip = trip

    if image != nil {
        print("Loaded from device")
        backgroundImage.image = image
        setLabels()
    } else {
//Doesn't freeze here
        let url = trip.coverPhotoUrl
        let ref = FIRStorage.storage().reference(forURL: url)
        ref.data(withMaxSize: 5*1024*1024, completion: { [weak self]
            (data, error) in
            if error != nil {
                print("Couldn't download image")
            } else {
                print("Image downloaded from storage")
                if let imageData = data {
                    if var image = UIImage(data: imageData) {
                        image = image.resizedImage(newSize: CGSize(width: (image.size.width)/8, height: (image.size.height)/8))
                        self?.backgroundImage.image = image
                        self?.setLabels()
                        TripsVC.imageCache.setObject(imageData as NSData, forKey: trip.coverUID as NSString)
                    }
                }
            }
        })
    }
}

0 个答案:

没有答案