从Firebase下载pdf并将其本地存储在iOS上

时间:2019-04-15 10:10:53

标签: ios swift firebase firebase-realtime-database

我需要从存储设备下载pdf并将其本地保存在iOS设备上,以便可以在“文件”中看到它。

这是我使用的文档中的代码:

override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        let userID = Auth.auth().currentUser!.uid
        print(userID)

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

        // Create a storage reference from our storage service
        let storageRef = storage.reference()

        // Create a reference to the file you want to download
        let islandRef = storageRef.child("pdf/sample.pdf")

        // Create local filesystem URL
        let localURL = URL(string: "pdf/sample.pdf")!

        // Download to the local filesystem
        let downloadTask = islandRef.write(toFile: localURL) { url, error in
            if let error = error {
                // Uh-oh, an error occurred!
            } else {
                // Local file URL for "images/island.jpg" is returned
            }
        }

    }

当我尝试运行此ViewController时,它不会崩溃但会引发以下错误:

"The file couldn’t be opened because the specified URL type isn’t supported." UserInfo={NSURL=pdf/sample.pdf}

Firebase存储中的文件保存在名为pdf/sample.pdf的文件夹中。最终,我希望从存储中获取引用并将其传递到RealtimeDatabase中,以便用户可以通过在表视图中查看有关它的详细信息来下载它。

2 个答案:

答案 0 :(得分:1)

我认为需要做的是指定要在哪个本地文件系统路径中保存下载的文档。因此,假设您要使用临时文件夹保存pdf。您可以尝试以下操作:

let tmporaryDirectoryURL = FileManager.default.temporaryDirectory
let localURL = tmporaryDirectoryURL.appendingPathComponent("sample.pdf")

islandRef.write(toFile: localURL) { url, error in
    if let error = error {
       print("\(error.localizedDescription)")
    } else {
       self.presentActivityViewController(withUrl: url)
    }
 }

下载文件以将其保存在“文件”应用中后,您将需要使用UIActivityViewController

func presentActivityViewController(withUrl url: URL) {
    DispatchQueue.main.async {
      let activityViewController = UIActivityViewController(activityItems: [url], applicationActivities: nil)
      activityViewController.popoverPresentationController?.sourceView = self.view
      self.present(activityViewController, animated: true, completion: nil)
    }
}

我尚未测试它,但我的假设是您收到此错误,因为您的localURL变量不是文件系统URL。

答案 1 :(得分:0)

打开文件时,您应该使用URL(string: String)来代替URL(fileURLWithPath: String)