Swift-如何打开在UserDefaults中存储位置的pdf文件?

时间:2018-09-05 05:00:02

标签: swift file pdf download nsuserdefaults

我一直在尝试使用Swift在我的应用程序上打开文件。这是我通过URL从Internet下载的PDF文件。下载部分对我来说效果很好,但是我无法找到一种方法来通过应用程序的本地位置打开相同的PDF文件,而无需再次下载。我知道下载后可以立即在Web视图中打开它,但我打算这样做,以便可以在没有Internet的情况下访问该文件。因此,为什么将文件位置存储在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
}

}

0 个答案:

没有答案