从TableViewCell Swift中的Firebase加载图像

时间:2017-12-22 21:46:50

标签: ios swift uitableview firebase alamofireimage

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

@IBOutlet weak var tableView: UITableView!

var storiesArray = [Stories]()

override func viewDidLoad() {
    super.viewDidLoad()

    retrieveStories()
}

我在这个函数中获取了imageDownloadURL,我在viewDidLoad()中调用

 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()
        })

    }
} 

获得所有数据后,我想从故事库中下载图片中的图片我现在在storyArray.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")
    }

如果当前显示单元格,则仅加载图像。这导致了许多问题。一个问题是,如果我滚动得比图像加载得快,它将显示在另一个单元格中。

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

1 个答案:

答案 0 :(得分:1)

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")
    }