Firebase存储downloadUrl完成处理程序始终返回错误

时间:2018-05-28 09:39:44

标签: swift firebase firebase-storage

所以我关注documentation,但我总是收到此错误:

  

出现错误:用户无权访问   GS://***-*****.appspot.com/(空)

虽然图片已成功上传。唯一的事情是,当调用完成处理程序时,它会返回一个错误,我无法获取图像路径。任何帮助表示赞赏。这是代码:

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:

service firebase.storage {
   match /b/my-project.appspot.com/o {
    match /{allPaths=**} {
      allow read, write;
    }
  }
}

2 个答案:

答案 0 :(得分:2)

The error occured because you're pointing to the Storage service to get the download URL.

storage.downloadURL

You should instead use Storage reference to get it.

imageReference.downloadURL

答案 1 :(得分:1)

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 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