1
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 method func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController { return self }

Hi all, above code does not work , the cache directory does not have my file that download.

GTeckHan Goh
  • 97
  • 1
  • 3
  • 12

0 Answers0