如何从我的iphone浏览我的应用程序的pdf文件,就像我能够通过ibooks浏览pdf文件一样?

问题描述 投票:0回答:2

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

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")
        }
ios swift iphone ios12
2个回答
0
投票

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

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)
}

0
投票

如果要在应用程序中查看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

© www.soinside.com 2019 - 2024. All rights reserved.