ios - 如何在 iOS 中打开文件?

标签 ios swift

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

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

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

    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。您可以在this上阅读相关内容。苹果文档页面。

通过谷歌搜索,您甚至应该看到一些示例实现。例如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
}

关于ios - 如何在 iOS 中打开文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46537575/

相关文章:

ios - 处理 iOS 异常的最佳方法

android - 如何检测另一个应用程序何时使用我的网络服务?

mkmapview - Swift - 添加 MKAnnotationView 到 MKMapView

swift - 一键执行多项操作

ios - 弹出现有 View Controller 并加载父 View Controller

swift - 运行和开发相同的 Swift macOS 应用程序

ios - UIButton 在 collectionView 单元格中不起作用

ios - 仅在从 API 接收到数据时显示 View

ios - 以编程方式/命令打开 iOS 开发人员菜单

ios - AVAudioPlayerNode 同时播放多首歌曲