将PDF文件下载到缓存目录在swift中不起作用

时间:2018-02-08 02:35:04

标签: ios swift pdf cache-control uidocumentinteraction

import UIKit

class MOViewController:UIViewController, UIDocumentInteractionControllerDelegate {
//my variable
var documentController: UIDocumentInteractionController = UIDocumentInteractionController()

override func viewDidLoad() {
    super.viewDidLoad()
//my pdf file
    downloadFileForfileObject(url: "https://d0.awsstatic.com/whitepapers/KMS-Cryptographic-Details.pdf")
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

}
//download file function
func downloadFileForfileObject(url: String) {  //Download pdf File asynchronosly
    let documentURL = NSURL(string: url)
    let documentsURLPath = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first! as NSURL

    let fileExtension = ((documentURL!.pathComponents)?.last)! as String
    let request: URLRequest = URLRequest(url: documentURL! as URL, cachePolicy: NSURLRequest.CachePolicy.returnCacheDataElseLoad, timeoutInterval: 60)
    let fileURLPath = documentsURLPath.appendingPathComponent("\(fileExtension)")

    let sessionConfig = URLSessionConfiguration.default
    let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)

    let task = session.dataTask(with: request) { (data, response, error) in
        if (error == nil) {
            // Success go to open url
            self.openSelectedDocumentFromURL(documentURLString: fileURLPath!.path)
        } else {
            print(error?.localizedDescription)
        }
    }
    task.resume()
    }

func openSelectedDocumentFromURL(documentURLString: String) {
    let documentURL: NSURL = NSURL(fileURLWithPath: documentURLString)
    documentController = UIDocumentInteractionController(url: documentURL as URL)
    documentController.delegate = self
    documentController.presentPreview(animated: true)
}


// MARK: - UIDocumentInteractionViewController delegate methods

// documentInteraction方法     func documentInteractionControllerViewControllerForPreview(_ controller:UIDocumentInteractionController) - > UIViewController {         回归自我     }

大家好,上面的代码不起作用,缓存目录没有我下载的文件。

0 个答案:

没有答案