[英]Loading images from Firebase in TableViewCell Swift
我正在嘗試從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中擁有的url下載圖像。
我在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")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.