无法从 Firebase 获取图像到 Table 视图
Unable to fetch Images from Firebase to Table View
Screenshot TableView有没有办法将 downloadURL
(link) 转换为 UIImage
到我的 TableViewController
?
func loadPost() {
Database.database().reference().child("Posts").observe(.childAdded, with: { (snapshot: DataSnapshot) in
if let userDict = snapshot.value as? [String: Any] {
let photoUrlString = userDict["photoUrl"] as! String
let post = Posts(photoUrlString: photoUrlString)
self.posts.append(post)
print(self.posts)
self.tableView.reloadData()
}
})
}
试试这个来下载图像。您可以在 cellForRowAtIndexPath
中使用它
func loadimage(_ url: URL)
{
DispatchQueue.global().async {
if let data1 = try? Data(contentsOf: url){
if let img = UIImage(data: data1){
DispatchQueue.main.async {
cell.imgView.image = img
}
}
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
cell.textLabel?.text = posts[indexPath.row].photoUrl
let postImage = posts[indexPath.row]
if let photoUrl = URL(string: postImage.photoUrl)
{
do {
let data = try Data(contentsOf: photoUrl)
cell.imageView?.image = UIImage (data: data)
} catch {
print("")
}
}
return cell
}
Screenshot TableView有没有办法将 downloadURL
(link) 转换为 UIImage
到我的 TableViewController
?
func loadPost() {
Database.database().reference().child("Posts").observe(.childAdded, with: { (snapshot: DataSnapshot) in
if let userDict = snapshot.value as? [String: Any] {
let photoUrlString = userDict["photoUrl"] as! String
let post = Posts(photoUrlString: photoUrlString)
self.posts.append(post)
print(self.posts)
self.tableView.reloadData()
}
})
}
试试这个来下载图像。您可以在 cellForRowAtIndexPath
中使用它func loadimage(_ url: URL)
{
DispatchQueue.global().async {
if let data1 = try? Data(contentsOf: url){
if let img = UIImage(data: data1){
DispatchQueue.main.async {
cell.imgView.image = img
}
}
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
cell.textLabel?.text = posts[indexPath.row].photoUrl
let postImage = posts[indexPath.row]
if let photoUrl = URL(string: postImage.photoUrl)
{
do {
let data = try Data(contentsOf: photoUrl)
cell.imageView?.image = UIImage (data: data)
} catch {
print("")
}
}
return cell
}