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 { 回归自我 }
大家好,上面的代码不起作用,缓存目录没有我下载的文件。