1
votes

So I am following the documentation but I always get this error:

There was an error: User does not have permission to access gs://***-*****.appspot.com/(null).

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.

Here is the code:

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

Also, these are my security rules @ Firebase Storage:

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

2 Answers

2
votes

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
votes

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