Fail to Upload an Image into Firebase Storage

39 views Asked by At

I use image picker so that the user can upload an image to their post from the library. Then I want to save the pictures in Firestore storage, through the following code:

public typealias UploadPictureCompletion = (Result<String, Error>) -> Void
public func uploadEventHeaderImage(with data: Data, fileName: String, completion: @escaping UploadPictureCompletion){
        bucket.child("event_images/\(fileName)").putData(data, metadata: nil, completion: {metadata, error in
            
            guard error == nil else{
                //failed
                print("failed to upload event image to firebase")
                completion(.failure(StorageErrors.failedToUpload))
                return
            }
            
            self.bucket.child("event_images/\(fileName)").downloadURL(completion: {url, error in
                guard let url = url else{
                    print("failed to get download url from firebase")
                    completion(.failure(StorageErrors.failedToGetDownloadURL))
                    return
                }
                let urlString = url.absoluteString
                print("download ur returned: \(urlString)")
                completion(.success(urlString))
            })
        })
        
    }

When calling this function, I do the following:

let filename = "\(eventId).png"
        guard let data = headerImage.pngData() else {
            
            return
            
        }
        
        
        StorageManager.shared.uploadEventHeaderImage(with: data,
                                                   fileName: filename,
                                                   completion: {result in
            switch result {
                
            case .success(let downloadUrl):
                UserDefaults.standard.set(downloadUrl, forKey: "event_image_url")
                print(downloadUrl)
            case .failure(let error):
                print("Storage manager error: \(error)")
            }
        })

In Firebase Storage I have created a folder called 'event_images'. When running the code, I get an error "failed to upload event image to firebase". What can be the problem in this case?

1

There are 1 answers

2
GGShin On
guard error == nil else{
                //failed
                print("failed to upload event image to firebase -- \(error)")
                completion(.failure(StorageErrors.failedToUpload))
                return
}

There are a bunch of possible reasons for failing. Printing out the error message itself as well will help you to get more precise information.