在 TableViewCell 中从 Firebase 加载图像 Swift

Loading images from Firebase in TableViewCell Swift

我正在尝试从我的 Firebase 数据库加载图像到我的 TableView 单元格中。 我正在使用 AlamofireImage。

@IBOutlet weak var tableView: UITableView!

var storiesArray = [Stories]()

override func viewDidLoad() {
    super.viewDidLoad()

    retrieveStories()
}

我在 viewDidLoad() 中调用的函数中获取 imageDownloadURL

 func retrieveStories() {

    let storiesDB = Database.database().reference().child("storyDetails")

    storiesDB.observe(.childAdded) { (snapshot) in

        let snapshotValue = snapshot.value as! Dictionary<String,String>
        let autor = snapshotValue["autor"]!
        let genre = snapshotValue["genre"]!
        let titel = snapshotValue["titel"]!
        let downloadURL = snapshotValue["imageDownloadURL"]


        let story = Stories()
        story.genre = genre
        story.titel = titel
        story.autor = autor
        story.downloadURL = downloadURL

        self.storiesArray.append(story)

        DispatchQueue.main.async(execute: {
            self.tableView.reloadData()
        })

    }
} 

获得所有数据后,我想从 url 中下载图像,我现在在 storiesArray.downloadURL

我在 cellForRowAtIndexPath 中这样做

let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! StoryDetailCell

    if storiesArray[indexPath.row].downloadURL != nil {
            Alamofire.request(indexPathRow.downloadURL!).responseImage { response in
                debugPrint(response)

                print(response.request as Any)
                print(response.response as Any)
                debugPrint(response.result)

                if let image = response.result.value {
                    print("image downloaded: \(image)")
                    DispatchQueue.main.async {
                        cell.storyImage.image = image
                    }

                }
            }
        } else if indexPathRow.downloadURL == nil {
            cell.storyImage.image = #imageLiteral(resourceName: "standard")
    }

仅当单元格当前显示时才会加载图像。这会导致很多问题。一个问题是,如果我滚动的速度快于图像加载的速度,它将显示在另一个单元格中。

我想知道如何处理这种情况。

let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! StoryDetailCell

    cell.storyImage.image = nil

    cell.tag += 1
    let tag = cell.tag

    if storiesArray[indexPath.row].downloadURL != nil {
        Alamofire.request(indexPathRow.downloadURL!).responseImage { response in

            if let image = response.result.value {
                if cell.tag == tag {
                    DispatchQueue.main.async {
                        cell.storyImage.image = image
                    }
                }
            }
        }
    } else if indexPathRow.downloadURL == nil {
        cell.storyImage.image = #imageLiteral(resourceName: "standard")
    }