ios 如何浏览pdf文件从我的iPhone为我的应用程序,就像我能够浏览pdf文件通过ibooks?

s5a0g9ez  于 2023-03-09  发布在  iOS
关注(0)|答案(2)|浏览(140)

就像使用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")
        }
njthzxwz

njthzxwz1#

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

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

jtw3ybtb2#

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

PDF查看-适用于iOS 11.0

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

WKWebView-适用于iOS 8.0系统

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

您也可以使用UIWebview来获得相同的结果,但它已被弃用。
或者,使用一个文件资源管理器库,您可以根据需要进行自定义。
https://developer.apple.com/documentation/pdfkit/pdfviewhttps://developer.apple.com/documentation/webkit/wkwebview

相关问题