我是不熟悉Swift的人,目前正在研究需要下载存储在Firebase云存储上的映像的应用程序。我遇到的一个问题是,我尝试使用直接从Firebase文档中下载的代码下载它,您可以在下面看到。
// Create a reference to the file you want to download
let islandRef = storageRef.child("images/island.jpg")
// Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
islandRef.getData(maxSize: 1 * 1024 * 1024) { data, error in
if let error = error {
// Uh-oh, an error occurred!
} else {
// Data for "images/island.jpg" is returned
let image = UIImage(data: data!)
}
}
但是您可以看到image属性似乎在该闭包中丢失了,但是显然我希望能够使用该图像并将其设置为我的应用程序中imageview的image属性。我想知道如何使该图像保留在.getData
的回调函数之外。您可以使用此:
let Ref = Storage.storage().reference(forURL: imageUrlUrl)
Ref.getData(maxSize: 1 * 1024 * 1024) { data, error in
if error != nil {
print("Error: Image could not download!")
} else {
yourImageView.image = UIImage(data: data!)
}
}
希望有帮助...
typealias Completion = (_ image: UIImage?, _ error: Error?) -> Void
func getImage(completion: @escaping Completion) {
/ Create a reference to the file you want to download
let islandRef = storageRef.child("images/island.jpg")
// Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
islandRef.getData(maxSize: 1 * 1024 * 1024) { data, error in
if let error = error {
Completion(nil, error)
// Uh-oh, an error occurred!
} else {
// Data for "images/island.jpg" is returned
let image = UIImage(data: data!)
Completion(image, nil)
}
}
}
如何使用
override func viewDidLoad() {
super.viewDidLoad()
getImage { [weak self](image, error) in
if let img = image {
yourImageView?.image = img
}
}
}
在这里您获得image
或error