【问题标题】:Swift 4: Fetch images from Firebase storage and display them in the table ViewSwift 4:从 Firebase 存储中获取图像并将它们显示在表格视图中
【发布时间】:2019-02-02 11:53:07
【问题描述】:

我还没有找到任何好的示例/代码来从 Firebase 存储/数据库中获取图像并将其显示在基本表格视图的单元格中。我看了here,但没有发现任何有用的东西。谁能举个完整的例子?

下面是我试图让它工作的代码:

import UIKit
import FirebaseStorage
import FirebaseDatabase
import FirebaseAuth
import Firebase

class TableViewController: UITableViewController {

        //TableView datasource methods

        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
            self.downloadImages(cell: cell, folderPath: "\(Storage.storage().reference().child((Auth.auth().currentUser?.uid)!).child("post\(takePicViewController().finalPost + PhotoArray.sharedInstance.numberPost)").child(ImageUploadManager().imageName))", success: { (img) in
                print(img)
            }) { (error) in
                print(error)
            }

//            cell.imageView?.image = PhotoArray.sharedInstance.photosArray[indexPath.row] as? UIImage
            return cell
        }

        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            let numberOfRowsInSection = PhotoArray.sharedInstance.photosArray
            return numberOfRowsInSection.count 
        }

    func downloadImages(cell: UITableViewCell, folderPath:String,success:@escaping (_ image:UIImage)->(),failure:@escaping (_ error:Error)->()){
        for i in 0 ..< 194{
            // Create a reference with an initial file path and name
            let reference = Storage.storage().reference().child((Auth.auth().currentUser?.uid)!).child("post\(takePicViewController().finalPost + PhotoArray.sharedInstance.numberPost)").child(ImageUploadManager().imageName)
            reference.getData(maxSize: (1 * 1024 * 1024)) { (data, error) in
                if let _error = error{
                    print(_error)
                    failure(_error)
                } else {
                    if let _data  = data {
                        let myImage:UIImage! = UIImage(data: _data)
                        success(myImage)
                    }
                }
//                let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
                cell.imageView?.image = UIImage(data: data!)
            }

        }
    }

}

我也试过下面的代码:

在 VC 开始时,我会执行以下操作:

    // Firebase services
var database: Database!
var storage: Storage!

// Initialize Database, Auth, Storage
override func viewDidLoad() {
    database = Database.database()
    storage = Storage.storage()
}

然后我调用 tableView_cellforRowAt indexPath 函数中的函数,如下所示。然后我返回单元格

       let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
       loadArrayOfImages(cell: cell)

       return cell

我调用的函数是这样的:

    func loadArrayOfImages(cell: UITableViewCell) {

    let dbRef = database.reference().child((Auth.auth().currentUser?.uid)!).child("post\(takePicViewController().finalPost + PhotoArray.sharedInstance.numberPost)").child(ImageUploadManager().imageName)
    dbRef.observe(.childAdded, with: { (snapshot) in
        // Get download URL from snapshot
        let downloadURL = snapshot.value as! String
        // Create a storage reference from the URL
        let storageRef = self.storage.reference(forURL: downloadURL)
        // Download the data, assuming a max size of 1MB (you can change this as necessary)
        storageRef.getData(maxSize: 10 * 1024 * 1024) { (data, error) -> Void in
            // Create a UIImage, add it to the array
            let pic = UIImage(data: data!)
            self.picArray.append(pic!)
            cell.imageView?.image = pic
        }
    })

   }
}

我似乎没有收到任何错误,应用程序也没有崩溃,但是当我按下按钮将我带到电视时,它只是空白。

【问题讨论】:

  • 不需要下载可以使用的图片SDWebImage直接传imageUrl。
  • 为什么是网页图片?这是 ios 应用程序,我们正在使用用户创建的图像
  • 如果您检查了上面的库,这是针对 iOS 应用程序的。它会异步下载特定UIImageView 的图像。不要误会它的名字。 :)
  • @AlexanderTheGreat 用于加载图片 stackoverflow.com/a/51746300/10150796

标签: ios firebase firebase-realtime-database swift4 firebase-storage


【解决方案1】:

这可能就像重新加载 tableView 一样简单。请记住,您对 Firebase 服务器的数据请求不会立即返回,因为它是网络调用,因此可能是您的表在数据返回之前已经“设置”了自己。要解决这个问题,您应该使用tableView.reloadData()。您可以将其放在 loadArrayOfImages() 函数的末尾,如下所示:

...
cell.imageView?.image = pic
tableView.reloadData()

【讨论】:

    猜你喜欢
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 2020-09-18
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    相关资源
    最近更新 更多