首页 > 解决方案 > 无法将图像从 Firebase 检索到 TableViewCell

问题描述

我一周前刚开始学习 Firebase,但现在我面临无法将图像从 Firebase 加载到我的 TableViewCell 的问题。我可以从 Firebase 实时数据库中检索文本信息和图像 URL 等数据,但无法使用这些 URL 在 TableViewCell 上启动图像。大家可以帮我找出问题吗?我可以检索文本信息以及图像 URL 等所有内容,但是如何使图像在单元格上弹出?您的所有帮助将不胜感激!

这是负责显示 TableViewCell 的 ViewController

import UIKit
import Firebase
import FirebaseStorage


class NewsFeedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    var rubthort:String = ""
    var linkRub:String?

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arrItem.count

    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "mycell", for: indexPath) as! NewsFeed
        // textlabel
        // detailtextlabel
        cell.textLabel?.text = arrItem[indexPath.row].name
        cell.detailTextLabel?.text = arrItem[indexPath.row].price
        //cell.imageView?.image = UIImage(named: "flower")
        // Get image
        let id = RetrieveData()

        if let imageLink = self.linkRub {
            let url = URL(string: imageLink)
            //let data = NSData(contentsOf: url!)
            URLSession.shared.dataTask(with: url!) { (data, response, error) in
                    // download hit an error so return out
                    if error != nil {
                        print(error)
                        return
                    }
                DispatchQueue.main.async {
                    cell.imageView?.image = UIImage(data: data!)

                }

            }.resume()
        }

        return cell

    }

    let ref = Database.database().reference()
    // Array of PlasticItem
    var arrItem = [RetrieveData]()

    @IBOutlet weak var tblView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        retrieveData()

    } // Ends of viewDidLoad

    func retrieveData() {
        // Getting a node from database
        let retRef = ref.child("item/electronic")
        // Observing data changes
        retRef.observe(DataEventType.value) { (dataSnapshot) in
            // Remove array item everytime there is a new reference to the data in Firebase
            self.arrItem.removeAll()
            // Check if there are any children or second object inside the parent object
            if dataSnapshot.childrenCount > 0 {
              // Loop over all children's object
              for post in dataSnapshot.children.allObjects as! [DataSnapshot] {
                    let object = post.value as! [String: Any]
                    let getName = object["name"] as! String
                    let getPrice = object["price"] as! String
                    let getImage = object["itemURL"] as! String
                    print(getName)
                    print(getPrice)
                    print(getImage)
                self.linkRub = getImage
                self.arrItem.append(RetrieveData(cat: "", name: getName, price: getPrice, rub: getImage))

                }
               self.tblView.reloadData()
            }// Ends of if statement
            else if dataSnapshot.childrenCount == 0{
                print("No Data Found")
            }
        } // Ends of retRef.observe
    } // Ends of retrieveData()
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
}

这是模型结构

import Foundation
import UIKit

struct RetrieveData{
    var cat: String
    var name: String
    var price: String
    var rub: String?

    init(){
        self.cat = ""
        self.name = ""
        self.price = ""
        self.rub = ""

    }
    init(cat:String, name:String, price:String, rub: String){
        self.cat = cat
        self.name = name
        self.price = price
        self.rub = rub
    }

}

标签: iosswiftfirebase-realtime-databasefirebase-storage

解决方案


推荐阅读