iosswiftfirebase-storage

How do I detect if a Firebase Storage file exists?


I'm writing a Swift extension on FIRStorageReference to detect if a file exists or not. I am calling metadataWithCompletion(). If the completion block's optional NSError is not set, I think it's safe to assume that the file exists.

If the NSError is set, either something went wrong or the file doesn't exist. The storage documentation on handling errors in iOS states that FIRStorageErrorCodeObjectNotFound is the type of error that I should be checking, but is doesn't resolve (possibly Swiftified into a shorter .Name-style constant?) and I'm not sure what I should be checking it against.

I'd like to be calling completion(nil, false) if FIRStorageErrorCodeObjectNotFound is set somewhere.

Here's my code so far.

extension FIRStorageReference {
    func exists(completion: (NSError?, Bool?) -> ()) {
        metadataWithCompletion() { metadata, error in
            if let error = error {
                print("Error: \(error.localizedDescription)")
                print("Error.code: \(error.code)")

                // This is where I'd expect to be checking something.

                completion(error, nil)
                return
            } else {
                completion(nil, true)
            }
        }
    }
}

Many thanks in advance.


Solution

  • You can check the error code like so:

    // Check error code after completion
    storageRef.metadataWithCompletion() { metadata, error in
      guard let storageError = error else { return }
      guard let errorCode = FIRStorageErrorCode(rawValue: storageError.code) else { return }
      switch errorCode {
        case .ObjectNotFound:
          // File doesn't exist
    
        case .Unauthorized:
          // User doesn't have permission to access file
    
        case .Cancelled:
          // User canceled the upload
    
        ...
    
        case .Unknown:
        // Unknown error occurred, inspect the server response
      }
    }