【问题标题】:How to browse pdf file from my iphone for my app, just like I am able to browse pdf file through ibooks?如何从我的 iphone 浏览我的应用程序的 pdf 文件,就像我能够通过 ibooks 浏览 pdf 文件一样?
【发布时间】:2019-07-09 12:19:04
【问题描述】:

就像使用UIImagePickerViewController 浏览 UIIMage。有没有办法在 Swift / 目标代码中浏览另一个文件?

if let fileURL = NSBundle.mainBundle().URLForResource("MyImage", withExtension: "jpg") {
            // Instantiate the interaction controller
            self.docController = UIDocumentInteractionController(URL: fileURL)
        }
        else {
            shareButton.enabled = false
            print("File missing! Button has been disabled")
        }

【问题讨论】:

  • @R.yan:关于您的编辑,请不要添加 please-help 恳求人们的问题。它根本不提高可读性,也不是我们在这里的目标。

标签: ios swift iphone ios12


【解决方案1】:

您只能访问文件夹中的文件。访问所有文件

let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
do {
    let fileURLs = try fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
    // process files
} catch {
    print("Error while enumerating files \(documentsURL.path): \(error.localizedDescription)")
}

如果你想单个文件看下面的代码:

// Get the document directory url
let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

do {
    // Get the directory contents urls (including subfolders urls)
    let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: [])
    print(directoryContents)

    // if you want to filter the directory contents you can do like this:
    let mp3Files = directoryContents.filter{ $0.pathExtension == "mp3" }
    print("mp3 urls:",mp3Files)
    let mp3FileNames = mp3Files.map{ $0.deletingPathExtension().lastPathComponent }
    print("mp3 list:", mp3FileNames)

} catch {
    print(error.localizedDescription)
}

【讨论】:

  • 有什么方法可以访问该文件夹吗?通过这段代码,我将无法获取文件名。我可以在我的应用程序中访问这些文件吗?请帮忙
  • 您可以使用第一个代码查看文档目录中的所有文件,如果您在文档目录中有该 pdf,则绝对可以访问它们。
  • 我要求的代码是从 .电话目录不是来自我的应用程序的应用程序内部目录。我希望访问 Ibook 中列出的 pdf。就像我们在 WhatsApp 中浏览 pdf 文件一样
【解决方案2】:

如果您想在应用中查看 PDF 文件,有两种方法。

PDFView - 适用于 iOS 11.0

let pdfDocument = PDFDocument(url: url)
pdfView.document = pdfDocument

WKWebView - 适用于 iOS 8.0

webView.loadRequest(URLRequest.init(url: url))

您也可以使用 UIWebview 来获得相同的结果,但它已被弃用。

或者,使用文件资源管理器库,您可以根据需要进行自定义。类似this

https://developer.apple.com/documentation/pdfkit/pdfview https://developer.apple.com/documentation/webkit/wkwebview

【讨论】:

  • 我要求的代码是从 .电话目录不是来自我的应用程序的应用程序内部目录。我希望访问 Ibook 中列出的 pdf。就像我们在 WhatsApp 中浏览 pdf 文件一样
猜你喜欢
  • 2017-01-14
  • 1970-01-01
  • 1970-01-01
  • 2013-09-01
  • 1970-01-01
  • 2015-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多