[英]Loading images from Firebase in TableViewCell Swift
Im trying to load images from my Firebase Database in my TableView Cell. 我正在尝试从TableView单元中的Firebase数据库加载图像。 Im using AlamofireImage. 我正在使用AlamofireImage。
@IBOutlet weak var tableView: UITableView!
var storiesArray = [Stories]()
override func viewDidLoad() {
super.viewDidLoad()
retrieveStories()
}
Im getting the imageDownloadURL in this function which i call in viewDidLoad() 我在此函数中获取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()
})
}
}
After I got all that data I want to download the images from the url´s which i now have in storiesArray.downloadURL 在获取所有数据之后,我想从我现在在storyArray.downloadURL中拥有的url下载图像。
Im doing that in cellForRowAtIndexPath 我在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")
}
The images are only getting loaded if the cell is currently displayed. 如果当前显示该单元格,则仅加载图像。 That causes many problems. 这会导致很多问题。 One Problem is that if I scroll faster than an image loads, it will be displayed in another cell. 一个问题是,如果滚动速度超过加载的图像,它将显示在另一个单元格中。
I would like to know how to handle a situation like this. 我想知道如何处理这种情况。
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")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.