就像我能够通过ibook来浏览pdf文件一样,如何从我的iPhone来浏览我的app的pdf文件?

时间:2019-02-15 11:02:28

标签: ios swift iphone ios12

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

2 个答案:

答案 0 :(得分: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)
}

答案 1 :(得分: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