UIDocumentInteractionController打开url

时间:2017-03-15 12:16:16

标签: ios swift swift3 uidocumentinteraction

我的网址是pdf扩展名。在点击网址时,我想向用户显示使用应用打开网址的选项(其中也应包含Safari浏览器)。我可以通过首先从文档目录中的url下载文件然后打开该文件来实现此目的。但我不想下载该文件,而是想让用户选择打开该URL。这是我尝试首先下载然后打开文件,但即使这没有显示选择应用程序的选项:

func openDocument(document: Document)
{
    let url = URL(string: document.documentUrl)
    var urlData = Data()
    do
    {
        urlData = try Data(contentsOf: url!)
    }
    catch
    {

    }

    if urlData != nil {
        var paths: [Any] = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        let temp = NSURL.fileURL(withPath: NSTemporaryDirectory(), isDirectory: true)
       // let temp = NSURL(
        let targetPath = temp.appendingPathComponent("\("name").pdf")
        do
        {
            //try urlData.write(to: URL(fileURLWithPath: targetPath), options: .atomic)
            try urlData.write(to: targetPath, options: .atomic)
        }
        catch let error as NSError {
            print("Could not write file", error.localizedDescription)
        }
    }

    var paths: [Any] = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let temp = NSURL.fileURL(withPath: NSTemporaryDirectory(), isDirectory: true)
    let targetPath = temp.appendingPathComponent("\("name").pdf")
    let pdfUrl = URL(fileURLWithPath: targetPath.absoluteString)
    if pdfUrl != nil {
        documentInteractionController = UIDocumentInteractionController(url: pdfUrl)
        documentInteractionController.name = document.documentName
        documentInteractionController.delegate = self
        documentInteractionController.presentPreview(animated: true)
    }
}

0 个答案:

没有答案