我正在尝试从Firebase存储中检索图像,但是由于某种原因,我检索到的图像始终是nil
。
var ref: DatabaseReference!
var storageRef: StorageReference!
var hallData = [Hall]()
override func viewDidLoad() {
let refHandle = Database.database().reference().child("hallData").observe(DataEventType.value, with: { (snapshot) in
let postDict = snapshot.value as? [String : AnyObject] ?? [:]
let values = Array(postDict.values)
//print(values)
let valueDict = values as! [[String:Any]]
for i in valueDict
{
var name = i["name"] as! String
var address = i["address"] as! String
var capacity = i["capacity"] as! String
var decorations = i["decorations"] as! String
var highPrice = i["highPrice"] as! String
var lowPrice = i["lowPrice"] as! String
var catering = i["catering"] as! String
var email = i["email"] as! String
self.storageRef = Storage.storage().reference().child("images").child(email)
var image: UIImage!
// Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
self.storageRef.getData(maxSize: 1 * 1024 * 1024) { data, error in
if let error = error {
print("PLASESEE")
print(error.localizedDescription)
// Uh-oh, an error occurred!
} else {
// Data for "images/island.jpg" is returned
let image = UIImage(data: data!)
}
}
print(image)
self.hallData.append(Hall(name2: name, capacity2: capacity, lowPrice2: lowPrice, highPrice2: highPrice, catering2: catering,decorations2: decorations, address2:address, image2: image, email2: email))
}
})
}
我不明白自己在做什么错,我遵循了Firebase存储上的api,查看了很多教程,但是我不断得到nil
答案 0 :(得分:0)
问题是您正尝试在getData闭包的 image var 之外使用。
self.storageRef.getData(maxSize: 1 * 1024 * 1024) { data, error in
if let error = error {
print("PLASESEE")
print(error.localizedDescription)
// Uh-oh, an error occurred!
} else {
// Data for "images/island.jpg" is returned
let image = UIImage(data: data!)
} <- closure ends here and image is only valid above this
}
print(image) <- image may not be populated at this point
self.hallData.append... image
}
该闭包是异步的,对self.hallData.append...
的调用将在将图像var填充到闭包中之前发生。代码比互联网快得多
在let image =
之后将语句移动到闭包中,它应该可以工作。
self.storageRef.getData(maxSize: 1 * 1024 * 1024) { data, error in
if let error = error {
print("An error occurred in downloading the image")
print(error.localizedDescription)
} else {
let image = UIImage(data: data!)
self.hallData.append... image
//reload your tableView or UI as self.hallData is now valid
}
}
如果采用这种方式,由于var image: UIImage!
之前没有功能,因此可以将其删除。否则,请在闭包中删除let before let image =。