我正在尝试制作一个简单的iOS应用程序(最新版本的Xcode,Swift 3)。它所要做的就是从Firebase数据库下载某种对象,并生成包含所有信息的动态列表。我确保应用程序可以正确下载所有信息,当然也可以,但是当生成de TableView的时间到来时,它会发生灾难性的失败。这是代码:
var ref: DatabaseReference!
var refHandle:UInt!
var productList = [Product]()
@IBOutlet weak var myTable: UITableView!
let cellId = "Product"
override func viewDidLoad() {
super.viewDidLoad()
ref = Database.database().reference()
myTable.delegate = self
myTable.dataSource = self
fetchProducts()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return productList.count
}
func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath as IndexPath) as! ProductTableViewCell
cell.nameLabel.text = productList[indexPath.row].name
cell.priceLabel.text = "" + (productList[indexPath.row].price?.description)!
let imageDict:NSDictionary = productList[indexPath.row].imageName!
let imageDownloaded = downloadImageProductFromFirebase(append: imageDict["hash"] as! String)
cell.picture.image = imageDownloaded
return cell
}
func fetchProducts(){
self.productList.removeAll()
refHandle = ref.child("products").observe(.childAdded, with: {(snapshot) in
print(snapshot)
var i = 0
for element in snapshot.children
{
i = i + 1
let item:DataSnapshot = element as! DataSnapshot
let key = item.key
let productsRef = self.ref!.child("products").child(key)
productsRef.observe(.value, with: { snapshot in
let productItem = (snapshot ).value as? [String : AnyObject]
let product = Product(name: productItem?["name"] as! String, image: productItem?["image"] as! NSDictionary, price: productItem?["price"] as! Float)
self.productList.append(product)
self.tableView.reloadData()
})
}
})
}
func downloadImageProductFromFirebase(append:String) -> UIImage{
let storage = Storage.storage()
var image = UIImage ()
var reference: StorageReference!
//all I did here was remove self before storage
reference = storage.reference(forURL: "gs://fridgeapp-3e2c6.appspot.com/productImages/" + append)
reference.downloadURL { (url, error) in
if(error != nil){
let data = NSData(contentsOf: url!)
image = UIImage(data: data! as Data)!
}
else {
image = #imageLiteral(resourceName: "ic_store")
}
}
return image
}
此外,我拍了一张显示错误的图片(它在控制台上没有说明,只是这个):Image of the error
毋庸置疑,我对Swift编程完全陌生,而且我在互联网上搜索,什么都没有......任何善良的灵魂都可以帮助我? 在此先感谢!!