【问题标题】:Unable to fetch Images from Firebase to Table View [closed]无法从 Firebase 获取图像到表视图 [关闭]
【发布时间】:2019-08-12 11:52:16
【问题描述】:

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

【问题讨论】:

    标签: ios swift xcode uiimage tableview


    【解决方案1】:

    试试这个下载图片。您可以在 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
                 }
               }
            }
        }
    }
    

    【讨论】:

    • 对不起,我不明白。
    • 在这种方法中,您只需要传递图像 url,它将返回该 url 上的图像。一旦您在 tableview 单元格上显示图像。
    • 谢谢!对于示例代码!我用“do, loop”语句做到了。
    【解决方案2】:
    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
        }
    

    【讨论】:

      猜你喜欢
      • 2017-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-22
      相关资源
      最近更新 更多