gpt4 book ai didi

ios - 如何从 firebase 存储 Swift 4 ios 检索图像

转载 作者:行者123 更新时间:2023-11-28 07:29:50 25 4
gpt4 key购买 nike

我正在尝试从 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

最佳答案

问题是您正试图在 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... 的调用将在闭包中填充图像变量之前发生。代码比互联网快得多

将该语句移到闭包中,紧跟在 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 image = 之前的 le​​t。

关于ios - 如何从 firebase 存储 Swift 4 ios 检索图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55201668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com