【问题标题】:How to open file in iOS?如何在 iOS 中打开文件?
【发布时间】:2018-03-14 05:40:40
【问题描述】:

我正在尝试在下载后打开一个.pdf 文件,该文件是使用 Alamofire 下载的。但我只看到使用“webview”。因此,应用程序会消耗大量内存并且不可行。

我想要的是用本机设备应用程序打开它。有什么建议?谢谢。

编辑:这是我的下载文件代码:

    var localPath: NSURL?

    Alamofire.download(.GET, url, destination: { (temporaryURL, response) in
    let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
    let pathComponent = response.suggestedFilename
    localPath = directoryURL.URLByAppendingPathComponent(pathComponent!)
    return localPath!
    })
    .response { (request, response, _, error) in

    if error != nil
    {
    // got an error in getting the data, need to handle it
    print("Error: \(error!)")

    }

    //print(response)
    print("Download file en:\(localPath!)")

    self.view.hideToastActivity()
    //self.actioncall()

    }

 }

我需要从本地路径打开文件...

【问题讨论】:

  • 听说过 UIDocumentInteractionController 吗??如果没有尝试阅读它。我相信这就是你所需要的 :) 快乐编码 :)
  • 你应该展示你已经做了什么。
  • 更新操作。我会读@SandeepBhandari

标签: ios swift


【解决方案1】:

您应该使用UIDocumentInteractionController。您可以在 this Apple 文档页面上了解它。

通过谷歌搜索,您甚至可以看到一些示例实现。例如here,您可以看到一些由“ma​​ttneub”完成的代码。

我再给你一个你可以使用的代码:

var documentInteractionController: UIDocumentInteractionController!

@IBAction func openDocument(sender: UIButton) {
  let URL: NSURL = NSBundle.mainBundle().URLForResource("yourPDF", withExtension: "pdf")!

    if (URL != "") {
        // Initialize Document Interaction Controller
        self.documentInteractionController = UIDocumentInteractionController(URL: URL)

        // Configure Document Interaction Controller
        self.documentInteractionController.delegate = self

        // Present Open In Menu
        self.documentInteractionController.presentOptionsMenuFromRect(sender.frame, inView: self.view, animated: true)
            //presentOpenInMenuFromRect
    }
}

// UIDocumentInteractionControllerDelegate
func documentInteractionControllerViewControllerForPreview(controller: UIDocumentInteractionController) -> UIViewController {
    return self
}

【讨论】:

  • 在这一行崩溃:让 URL: NSURL = NSBundle.mainBundle().URLForResource("yourPDF", withExtension: "pdf")! ...错误:致命错误:在展开可选值时意外发现 nil...线程 1 exc_bad_instruction (code=exc_i386_invop subcode=0x0)
  • 你的队列中没有 nil。但乐于助人。快乐编码:)
  • 还有一个问题。这适用于应用程序根目录中的 pdf 文件,但如果我使用 localpath(file:///Users/informatica/Library/Developer/CoreSimulator/Devices/6ABF0CE7-FE77-4D6F-9331-120A344B7396/data/Containers/ Data/Application/847D3998-5A9D-4741-9A54-DC71C9225F98/Documents/109.pdf)它不起作用或者我没有很好地实现它。我需要一个真实的设备或者可以用模拟器执行?。
  • 在模拟器上执行起来比较困难。请在真实设备上尝试。
猜你喜欢
  • 1970-01-01
  • 2021-09-28
  • 2014-08-10
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-28
相关资源
最近更新 更多