Swift Firebase UICollectionView - 图像缩略图不一致

Swift Firebase UICollectionView - Image thumbnails inconsistent

我正在使用 UICollectionView 显示从 firebase 下载的图像。问题是下载缩略图非常不一致。有时加载正确,但大多数时候缩略图重复或位于错误的单元格中。

Firebase 下载

func downloadImages(refreshing: Bool, refreshControl: UIRefreshControl?) {
        self.posts.removeAll()
        self.collectionViews.reloadData()
        let ref = Database.database().reference().child("posts")
        MBProgressHUD.showAdded(to: self.view, animated: true)
        ref.queryOrdered(byChild: "businessName").observe(.childAdded, with: { snapshot in
            if let dict = snapshot.value as? NSDictionary {
                self.posts = []
                for item in dict {
                    let json = JSON(item.value)
                    let uid = json["uid"].stringValue
                    var name: String = json["businessName"].stringValue
                    let address: String = json["businessStreet"].stringValue
                    let state: String = json["businessCity"].stringValue
                    let caption: String = json["caption"].stringValue
                    let downloadURL: String = json["download_url"].stringValue
                    let timestamp = json["timestamp"].doubleValue
                    let date = Date(timeIntervalSince1970: timestamp/1000)
                    let postID: String = json["postID"].stringValue

                    let lat = json["businessLatitude"].doubleValue
                    let long = json["businessLongitude"].doubleValue
                    let businessLocation = CLLocation(latitude: lat, longitude: long)

                    let latitude = self.locationManager.location?.coordinate.latitude
                    let longitude = self.locationManager.location?.coordinate.longitude
                    let userLocation = CLLocation(latitude: latitude!, longitude: longitude!)

                    let distanceInMeters: Double = userLocation.distance(from: businessLocation)
                    let distanceInMiles: Double = distanceInMeters * 0.00062137
                    let distanceLabelText = String(format: "%.2f miles away", distanceInMiles)
                    //let distanceLabelText = "Not Available"

                    let usersReference = Database.database().reference(withPath: "users").queryOrderedByKey().queryEqual(toValue: uid)
                    usersReference.observeSingleEvent(of: .value, with: { snapshot in
                        if let dict = snapshot.value as? NSDictionary {
                            let userInfo = dict.allValues[0]
                            let userJSON = JSON(userInfo)
                            name = userJSON["name"].stringValue

                        }
                        let post = Post(uid: uid, caption: caption, downloadURL: downloadURL, name: name, date: date, address: address, state: state, distance: distanceLabelText, postID: postID)
                        self.collectionViews.reloadData()
                        self.posts.append(post)
                        self.posts.sort {[=11=].distance.compare(.distance) == .orderedAscending}
                        //self.collectionViews.reloadData()


                    })
                }
            }
            if refreshing {
                self.posts.removeAll()
                self.collectionViews.reloadData()
                refreshControl?.endRefreshing()
            }
            MBProgressHUD.hide(for: self.view, animated: true)
        })

    }

UICollectionView 单元格

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
        cell.postImage.image = nil
        cell.postImage.sd_cancelCurrentImageLoad()
        if self.posts[indexPath.row].downloadURL != nil {
            cell.postImage.downloadImagezzz(from: self.posts[indexPath.row].downloadURL)
        } else {
            print("\n \(indexPath.row) could not return a value for pathToImage256 from Post. \n")
        }

        return cell
    }

下载并设置图片

extension UIImageView {
    func downloadImagezzz(from imgURL: String) {
        let url = URLRequest(url: URL(string: imgURL)!)

        let task = URLSession.shared.dataTask(with: url) {
            (data, responds, error) in

            if error != nil {
                print(error!)
                return
            }

            DispatchQueue.main.async {
                self.image = UIImage(data: data!)

            }
        }
        task.resume()
    }
}

我认为问题出在标题为 "Download and set image" 的最后一部分。

你用sd_cancelCurrentImageLoad的方法不用SDWebImage的下载图片方法就奇怪了。

使用下面的方法代替 downloadImagezzz 将解决问题

cell.postImage.sd_setImage(with: URL(string: self.posts[indexPath.row].downloadURL), placeholderImage: nil)