如何检测Firebase存储文件是否存在? [英] How do I detect if a Firebase Storage file exists?

查看:87
本文介绍了如何检测Firebase存储文件是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在FIRStorageReference上编写Swift扩展名,以检测文件是否存在.我正在呼叫metadataWithCompletion().如果未设置完成块的可选NSError,我认为可以安全地假定该文件存在.

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.

如果设置了NSError,则可能是出现问题或文件不存在. 有关处理iOS中错误的存储文档指出,FIRStorageErrorCodeObjectNotFound是我应该检查但无法解决的错误类型(可能已化为更短的.Name样式常量?),而且我不确定应该针对什么错误进行检查.

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.

如果FIRStorageErrorCodeObjectNotFound设置在某处,我想打电话给completion(nil, false).

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

非常感谢.

推荐答案

您可以像这样检查错误代码:

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

这篇关于如何检测Firebase存储文件是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆