ios - 在 iOS 中使用 Swift 保存 PDF 文件并显示它们

标签 ios swift pdf pdfkit

我想构建一个应用程序,其中还包括在应用程序内显示和保存 PDF 并在表格 View 中显示它们(作为文件系统)并在我点击一个 PDF 时打开它们的可能性。

这是我的重要问题:

<强>1。如何在我的应用程序上本地保存 PDF(例如,如果用户可以输入 URL)以及它将保存在何处?

<强>2。保存后,如何在表格 View 中显示所有本地存储文件并打开它们?

最佳答案

由于有几个人提出这个要求,这里相当于 Swift 中的第一个答案:

//The URL to Save
let yourURL = NSURL(string: "http://somewebsite.com/somefile.pdf")
//Create a URL request
let urlRequest = NSURLRequest(URL: yourURL!)
//get the data
let theData = NSURLConnection.sendSynchronousRequest(urlRequest, returningResponse: nil, error: nil)

//Get the local docs directory and append your local filename.
var docURL = (NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)).last as? NSURL

docURL = docURL?.URLByAppendingPathComponent( "myFileName.pdf")

//Lastly, write your file to the disk.
theData?.writeToURL(docURL!, atomically: true)

此外,由于此代码使用同步网络请求,我强烈建议将其分派(dispatch)到后台队列:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
    //The URL to Save
    let yourURL = NSURL(string: "http://somewebsite.com/somefile.pdf")
    //Create a URL request
    let urlRequest = NSURLRequest(URL: yourURL!)
    //get the data
    let theData = NSURLConnection.sendSynchronousRequest(urlRequest, returningResponse: nil, error: nil)

    //Get the local docs directory and append your local filename.
    var docURL = (NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)).last as? NSURL

    docURL = docURL?.URLByAppendingPathComponent( "myFileName.pdf")

    //Lastly, write your file to the disk.
    theData?.writeToURL(docURL!, atomically: true)
})

第二个问题的答案在 Swift 中:

//Getting a list of the docs directory
let docURL = (NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last) as? NSURL

//put the contents in an array.
var contents = (NSFileManager.defaultManager().contentsOfDirectoryAtURL(docURL!, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, error: nil))
//print the file listing to the console
println(contents)

关于ios - 在 iOS 中使用 Swift 保存 PDF 文件并显示它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29479812/

相关文章:

ios持久化存储框架

pdf - Ghostscript 呈现丑陋的文字

python - 打开 pdf 并使用 python pandas 阅读表格

ios - 将数据传递给自定义 View 然后执行函数是一种好方法吗?

ios - Fat XIB 的内存问题

swift - 如何在 Swift 中获取从 NSURLSessionDataTask 返回的数据

swift - 出现错误 : No such module 'Alamofire' while using the Alamofire. Playground

python - 使用 PyPDF2 去除 PDF 上的水印

ios - 运行时属性和实际属性之间的性能差异是什么?

ios - 如何在 Swift 中从 ConstUnsafePointer 创建 CStirng