WepsTech
Your Daily Dose of Tech News
I’ve been working on an App that requires me to download PDF files, store it, and to view it. I thought to write a tutorial and make a video and share with YouTube. So that, other person also can take the benefit of this. In this tutorial, I have cover Download and store a file in iOS. This task contains the following topics here.
For achieving all these we have to write some code below. First we will write the code for downloading the file. which is given as.
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()
Very good, Now write one more extension code for URLSessionDownloadDelegate, So that we can handle the file storage.
extension ViewController : URLSessionDownloadDelegate { func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { print("File Downloaded Location- ", location) guard let url = downloadTask.originalRequest?.url else { return } let docsPath = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] let destinationPath = docsPath.appendingPathComponent(url.lastPathComponent) try? FileManager.default.removeItem(at: destinationPath) do{ try FileManager.default.copyItem(at: location, to: destinationPath) self.pdfUrl = destinationPath print("File Downloaded Location- ", self.pdfUrl ?? "NOT") }catch let error { print("Copy Error: \(error.localizedDescription)") } } }
Above all, Used for downloading the file and store the file into proper location. After I pressed download, the file downloaded persisted less than a second, and then it was killed by the system.
This behaviour behaves the same on both simulator and physical machine. For finding the path of downloaded file in Simulator.
Open ~/Library/Developer/CoreSimulator/Devices into finder. And complete location looks like.
Temp file –file:///Users/pushpendra/Librar……D/tmp/CFNetworkDownload_tijImV.tmp
Actual file – file:///Users/pushpendra/Library…..Caches/swift_tutorial.pdf
Now crate a PDFViewController for opening the PDF file.
// // PDFViewController.swift // Download File // // Created by Pushpendra on 22/02/20. // Copyright © 2020 Pushpendra. All rights reserved. // import UIKit import PDFKit class PDFViewController: UIViewController { var pdfView = PDFView() var pdfURL : URL! override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(pdfView) if let document = PDFDocument(url: pdfURL){ pdfView.document = document } DispatchQueue.main.asyncAfter(deadline: .now()+3, execute: { self.dismiss(animated: true, completion: nil) }) } override func viewDidLayoutSubviews() { pdfView.frame = self.view.frame } }
Great, Now write some code for opening the PDF File.
Now we’ve successfully placed the downloaded PDF into the proper place for users to access. It’s time to view it with PDFView from PDFKit, which is a convenient framework provided by Apple since the release of iOS 11.
Even though many tutorials of PDFKit uses storyboard to create PDFView by assigning the property to a UIView, it does not support in Xibs. Thus here I’m going to instantiate it programmatically.
let pdfView = PDFViewController() pdfView.pdfURL = self.pdfUrl present(pdfView, animated: true, completion: nil)
Very good, Now below is the complete code of ViewController.
// // ViewController.swift // Download File // // Created by Pushpendra on 22/02/20. // Copyright © 2020 Pushpendra. All rights reserved. // import UIKit class ViewController: UIViewController { var pdfUrl : URL? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func download_btn(_ 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() } @IBAction func open_pdf(_ sender: Any) { let pdfView = PDFViewController() pdfView.pdfURL = self.pdfUrl present(pdfView, animated: true, completion: nil) } } extension ViewController : URLSessionDownloadDelegate { func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { print("File Downloaded Location- ", location) guard let url = downloadTask.originalRequest?.url else { return } let docsPath = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] let destinationPath = docsPath.appendingPathComponent(url.lastPathComponent) try? FileManager.default.removeItem(at: destinationPath) do{ try FileManager.default.copyItem(at: location, to: destinationPath) self.pdfUrl = destinationPath print("File Downloaded Location- ", self.pdfUrl ?? "NOT") }catch let error { print("Copy Error: \(error.localizedDescription)") } } }
In Conclusion, You have achieved your goal. For more information please watch the related video on the given LINK.
In addition, There are few more tutorial, Which may help you for good and stable iOS development.
ปั้มไลค์
Like!! Really appreciate you sharing this blog post.Really thank you! Keep writing.