Created
October 17, 2017 13:57
-
-
Save MatthiasLamoureux/d3820f64b3e0c2b07b8f19ae25cb8a30 to your computer and use it in GitHub Desktop.
Quick and dirty share PDF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ViewController.swift | |
// PDFWebView | |
// | |
// Created by Matthias Lamoureux on 16/10/2017. | |
// Copyright © 2017 Serli SAS. All rights reserved. | |
// | |
import UIKit | |
import WebKit | |
class ViewController: UIViewController, WKNavigationDelegate, URLSessionDownloadDelegate { | |
@IBOutlet var webView: WKWebView! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
webView.navigationDelegate = self | |
// Do any additional setup after loading the view, typically from a nib. | |
let address = "http://ocr86.fr/lassociation/" | |
let url = URL(string: address)! | |
let request = URLRequest(url: url) | |
webView.load(request) | |
} | |
override func didReceiveMemoryWarning() { | |
super.didReceiveMemoryWarning() | |
// Dispose of any resources that can be recreated. | |
} | |
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { | |
if let url = navigationAction.request.url, | |
url.path.lowercased().hasSuffix(".pdf") { | |
processPDF(url: url) | |
decisionHandler(.cancel) | |
} | |
else { | |
decisionHandler(.allow) | |
} | |
} | |
func processPDF(url: URL) { | |
UIApplication.shared.isNetworkActivityIndicatorVisible = true | |
let config = URLSessionConfiguration.background(withIdentifier: "com.serli.pdf-download.background") | |
let session = URLSession(configuration: config, delegate: self, delegateQueue: OperationQueue()) | |
let task = session.downloadTask(with: url) | |
task.resume() | |
} | |
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { | |
sharePDF(at: location.path) | |
} | |
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { | |
DispatchQueue.main.async { | |
UIApplication.shared.isNetworkActivityIndicatorVisible = false | |
} | |
} | |
func sharePDF(at path: String) { | |
guard | |
FileManager.default.fileExists(atPath: path), | |
let document = NSData(contentsOfFile: path) | |
else { return } | |
let activityViewController: UIActivityViewController = UIActivityViewController(activityItems: [document], applicationActivities: nil) | |
activityViewController.popoverPresentationController?.sourceView = self.view | |
present(activityViewController, animated: true, completion: nil) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment