import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } @IBAction func downloadButtonPressed(_ sender: Any) { guard let url = URL(string: "https://www.tutorialspoint.com/swift/swift_tutorial.pdf") else { return } let urlSession = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue()) let downloadTask = urlSession.downloadTask(with: url) downloadTask.resume() } } extension ViewController: URLSessionDownloadDelegate { func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { print("downloadLocation:", location) } }
extension ViewController: URLSessionDownloadDelegate { func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { print("downloadLocation:", location) // create destination URL with the original pdf name guard let url = downloadTask.originalRequest?.url else { return } let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let destinationURL = documentsPath.appendingPathComponent(url.lastPathComponent) // delete original copy try? FileManager.default.removeItem(at: destinationURL) // copy from temp to Document do { try FileManager.default.copyItem(at: location, to: destinationURL) self.pdfURL = destinationURL } catch let error { print("Copy Error: \(error.localizedDescription)") } } }
@IBAction func openPDFButtonPressed(_ sender: Any) { let pdfViewController = PDFViewController() pdfViewController.pdfURL = self.pdfURL present(pdfViewController, animated: false, completion: nil) }
import UIKit import PDFKit class PDFViewController: UIViewController { var pdfView = PDFView() var pdfURL: URL! override func viewDidLoad() { super.viewDidLoad() view.addSubview(pdfView) if let document = PDFDocument(url: pdfURL) { pdfView.document = document } DispatchQueue.main.asyncAfter(deadline: .now()+3) { self.dismiss(animated: true, completion: nil) } } override func viewDidLayoutSubviews() { pdfView.frame = view.frame } }
Source: https://habr.com/ru/post/430860/
All Articles