问题描述
因此,我正在遵循文档,但是我总是能得到这个错误:
So I am following the documentation but I always get this error:
图像已成功上传.唯一的事情是,当完成处理程序被调用时,它将返回一个错误,而我无法获取图像路径.
The images are uploaded successfully though. The only thing is that when the completion handler gets called, it returns an error and I cannot fetch the image path.
这是代码:
func uploadImage(_ image: UIImage, completion: @escaping (String?, Error?) -> Void) {
let filename = "\(Date().timeIntervalSince1970)"
let imageReference = storage.child(FirestoreStorage.dishImagesPath).child(filename)
guard let imageData = UIImageJPEGRepresentation(image, 0.8) else {
completion(nil, CommonError.imageConversionError)
return
}
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
imageReference.putData(imageData, metadata: metadata, completion: { [storage] (metadata, error) in
storage.downloadURL(completion: { (url, error) in
guard let url = url else {
completion(nil, error)
return
}
completion(url.absoluteString, nil)
})
})
}
此外,这是我在Firebase Storage上的安全规则:
Also, these are my security rules @ Firebase Storage:
service firebase.storage {
match /b/my-project.appspot.com/o {
match /{allPaths=**} {
allow read, write;
}
}
}
推荐答案
好的,所以我能够解决该问题并在完成处理程序中获取图像路径.哪里错了?在这两行中:
Okay, so I was able to fix that and get the image path in the completion handler. What was wrong? It is in these two lines:
imageReference.putData(imageData, metadata: metadata, completion: { [storage] (metadata, error) in
storage.downloadURL(completion: { (url, error) in
imageReference 是对图像本身的引用, 存储 是对全局存储的引用.这种误解来自文档.所以应该是这样:
imageReference is a reference to the image itself and storage is a reference to the global storage. This misunderstanding came from the docs. So the way it should be:
imageReference.putData(imageData, metadata: metadata, completion: { (metadata, error) in
imageReference.downloadURL(completion: { (url, error) in
这篇关于Firebase存储downloadUrl完成处理程序始终返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!