Swift-如何打开存储在UserDefaults中的pdf文件?
我一直在尝试使用Swift在我的应用程序上打开一个文件。这是一个PDF文件,我通过URL从互联网上下载。下载部分对我来说很好,但我无法找到一种方法,通过我的应用程序上的本地位置打开相同的PDF文件,而不必再次下载。我知道我可以在下载后立即在网络视图中打开它,但我正计划这样做,这样文件就可以在没有互联网的情况下访问;因此,我将文件位置存储在UserDefaults中 我在网上到处阅读,也在youtube上搜索视频,但似乎找不到任何方法来实现这一点。另外,如果我不应该使用UserDefaults,或者因为我不想访问任何服务器而这样做似乎是最好的方式,请纠正我 到目前为止,我使用的代码如下:Swift-如何打开存储在UserDefaults中的pdf文件?,swift,file,pdf,download,nsuserdefaults,Swift,File,Pdf,Download,Nsuserdefaults,我一直在尝试使用Swift在我的应用程序上打开一个文件。这是一个PDF文件,我通过URL从互联网上下载。下载部分对我来说很好,但我无法找到一种方法,通过我的应用程序上的本地位置打开相同的PDF文件,而不必再次下载。我知道我可以在下载后立即在网络视图中打开它,但我正计划这样做,这样文件就可以在没有互联网的情况下访问;因此,我将文件位置存储在UserDefaults中 我在网上到处阅读,也在youtube上搜索视频,但似乎找不到任何方法来实现这一点。另外,如果我不应该使用UserDefaults,或
import UIKit
import WebKit
class ViewController: UIViewController, URLSessionDownloadDelegate, UIDocumentInteractionControllerDelegate {
var downloadTask: URLSessionDownloadTask!
var backgroundSession: URLSession!
let name = "Accounting"
@IBAction func startDownload(_ sender: AnyObject) {
let url = URL(string: "https://pastpapers.papacambridge.com/Cambridge%20International%20Examinations%20(CIE)/AS%20and%20A%20Level/Accounting%20(9706)/2005%20Nov/9706_w05_qp_4.pdf")!
downloadTask = backgroundSession.downloadTask(with: url)
downloadTask.resume()
}
@IBAction func pause(_ sender: AnyObject) {
if downloadTask != nil{
downloadTask.suspend()
}
}
@IBAction func resume(_ sender: AnyObject) {
if downloadTask != nil{
downloadTask.resume()
}
}
@IBAction func cancel(_ sender: AnyObject) {
if downloadTask != nil{
downloadTask.cancel()
}
}
@IBOutlet var progressView: UIProgressView!
@IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
let backgroundSessionConfiguration = URLSessionConfiguration.background(withIdentifier: "backgroundSession")
backgroundSession = Foundation.URLSession(configuration: backgroundSessionConfiguration, delegate: self, delegateQueue: OperationQueue.main)
progressView.setProgress(0.0, animated: false)
}
override func viewWillAppear(_ animated: Bool) {
if let file = UserDefaults.standard.object(forKey: "Biology") {
print(file) //prints the file location where UserDefaults stores it in
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func showFileWithPath(path: String){
let isFileFound:Bool? = FileManager.default.fileExists(atPath: path)
if isFileFound == true{
UserDefaults.standard.set(path, forKey: "Biology")
let viewer = UIDocumentInteractionController(url: URL(fileURLWithPath: path))
viewer.delegate = self
viewer.presentPreview(animated: true)
}
}
//URLSessionDownloadDelegate
func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL){
let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentDirectoryPath:String = path[0]
let fileManager = FileManager()
let destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath.appendingFormat("/\(name).pdf"))
if fileManager.fileExists(atPath: destinationURLForFile.path){
showFileWithPath(path: destinationURLForFile.path)
}
else{
do {
try fileManager.moveItem(at: location, to: destinationURLForFile)
// show file
showFileWithPath(path: destinationURLForFile.path)
}catch{
print("An error occurred while moving file to destination url")
}
}
}
func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64){
progressView.setProgress(Float(totalBytesWritten)/Float(totalBytesExpectedToWrite), animated: true)
}
//URLSessionTaskDelegate
func urlSession(_ session: URLSession,
task: URLSessionTask,
didCompleteWithError error: Error?){
downloadTask = nil
progressView.setProgress(0.0, animated: true)
if (error != nil) {
print(error!.localizedDescription)
}else{
print("The task finished transferring data successfully")
}
}
//UIDocumentInteractionControllerDelegate
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController
{
return self
}
}您需要发布相关代码。演示如何下载和存储文件。显示如何在UserDefaults中存储位置。显示稍后如何尝试从本地位置打开文件。显示变量的相关值。解释你对代码的实际问题。嗨@rmaddy,对不起,我现在更新了代码,包含了我使用的所有代码。也许这现在会有帮助。@Danny您在哪里显示文件?(找不到行。)我在
WKWebView
上遇到问题,并使用了PDFView
,但如果您不显示它,这也没用。