【问题标题】:Firebase Storage download to local file errorFirebase 存储下载到本地文件错误
【发布时间】:2017-02-18 23:44:39
【问题描述】:

我正在尝试从我的 Firebase 存储中下载图像 f5bd8360.jpeg
当我使用 dataWithMaxSize:completion 将此图像下载到内存时,我可以下载它。

当我尝试使用 writeToFile: 实例方法将图像下载到本地文件时出现问题。

我收到以下错误:

Optional(Error Domain=FIRStorageErrorDomain Code=-13000 "An unknown
error occurred, please check the server response."
UserInfo={object=images/f5bd8360.jpeg,
bucket=fir-test-3d9a6.appspot.com, NSLocalizedDescription=An unknown
error occurred, please check the server response.,
ResponseErrorDomain=NSCocoaErrorDomain, NSFilePath=/Documents/images,
NSUnderlyingError=0x1700562c0 {Error Domain=NSPOSIXErrorDomain Code=1
"Operation not permitted"}, ResponseErrorCode=513}"

这是我的 Swift 代码的 sn-p:

@IBAction func buttonClicked(_ sender: UIButton) {

        // Get a reference to the storage service, using the default Firebase App
        let storage = FIRStorage.storage()

        // Get reference to the image on Firebase Storage
        let imageRef = storage.reference(forURL: "gs://fir-test-3d9a6.appspot.com/images/f5bd8360.jpeg")

        // Create local filesystem URL
        let localURL: URL! = URL(string: "file:///Documents/images/f5bd8360.jpeg")

        // Download to the local filesystem
        let downloadTask = imageRef.write(toFile: localURL) { (URL, error) -> Void in
            if (error != nil) {
                print("Uh-oh, an error occurred!")
                print(error)
            } else {
                print("Local file URL is returned")
            }
        }
    }

我发现another question 遇到了同样的错误,但从未得到完整的回答。我认为这个提议是对的。我没有写入文件的权限。但是,我不知道如何获得权限。有什么想法吗?

【问题讨论】:

  • 根据另一个答案,您可能无权写信给file:///Documents/images/f5bd8360.jpeg。很可能您有写入/Documents 的权限,但/Documents/images 可能不存在,并且不是自动创建的,因此由于无法写入文件而失败。确保你有所有正确的目录可以写入。
  • 那么,如何在iOS中创建目录呢?特别是图像目录。
  • 抱歉,我尝试使用新的 localURL 运行我的代码到“file:///Documents/f5bd8360.jpeg”,但我仍然遇到同样的错误

标签: ios swift firebase firebase-storage


【解决方案1】:

问题是在你写这行的那一刻:

let downloadTask = imageRef.write(toFile: localURL) { (URL, error) -> Void in
etc.

您还没有写入该 (localURL) 位置的权限。要获得权限,您需要在尝试向localURL写入任何内容之前编写以下代码

let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let localURL = documentsURL.appendingPathComponent("filename")

通过这样做,您会将文件写入设备上的以下路径(如果您在真实设备上进行测试): file:///var/mobile/Containers/Data/Application/XXXXXXXetc.etc./Documents/filename

如果您在模拟器上进行测试,那么路径显然会在计算机上的某个位置。

【讨论】:

  • 我的 downloadTask 已经按照您的建议设置好了。但是,我收到警告 - 不可变值“downloadTask”的初始化从未使用过;考虑替换为“_”的分配或将其删除它位于从 Firebase 下载 plist 的 func 中,并且工作正常。所以我想知道为什么会出现这个警告?
  • 这完全正常。您看到的是一个编译器警告,基本上是说您的变量已创建但未再次使用。您可以将 downloadTask 替换为下划线。请记住,在某些时候您实际上可能需要使用 downloadTask。例如。您可能想观察下载状态(成功/失败)或下载进度等。
猜你喜欢
  • 1970-01-01
  • 2017-08-20
  • 2017-08-22
  • 2018-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-01
  • 1970-01-01
相关资源
最近更新 更多