Swift: Read pdf file into pdf application reader

后端 未结 2 453
悲哀的现实
悲哀的现实 2021-01-23 20:22

How can I display all applications that can read pdf file (adobe pdf reader for example) when a button is clicked? I searched but I found that the majority use UIWebView to disp

2条回答
  •  孤城傲影
    2021-01-23 21:01

    You can go with UIDocumentInteractionController, it will handle all for you like zooming pdf, scrolling, showing suitable app to handle the pdf.

    SWIFT 2.3:

    import UIKit
    
    class ViewController:UIViewController, UIDocumentInteractionControllerDelegate {
    
    var documentController: UIDocumentInteractionController = UIDocumentInteractionController()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        downloadFileForfileObject("https://d0.awsstatic.com/whitepapers/KMS-Cryptographic-Details.pdf")
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    func downloadFileForfileObject(url: String) { //Download pdf File asynchronosly
        let documentURL = NSURL(string: url)
        let documentsURLPath = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask).first! as NSURL
    
        let fileExtension = ((documentURL!.pathComponents)?.last)! as String
        let request: NSURLRequest = NSURLRequest(URL: documentURL!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 60)
        let fileURLPath = documentsURLPath.URLByAppendingPathComponent("\(fileExtension)")
    
        let sessionCobfig = NSURLSessionConfiguration()
        let session = NSURLSession(configuration: sessionCobfig, delegate: nil, delegateQueue: nil)
        let task = session.dataTaskWithRequest(request) { (data, response, error) in
            if error == nil {
                self.openSelectedDocumentFromURL((fileURLPath?.path!)!)
            } else {
                print(error?.localizedDescription)
            }
        }
        task.resume()
    }
    
    func openSelectedDocumentFromURL(documentURLString: String) {
        let documentURL: NSURL = NSURL(fileURLWithPath: documentURLString)
        documentController = UIDocumentInteractionController(URL: documentURL)
        documentController.delegate = self
        documentController.presentPreviewAnimated(true)
    }
    
    // MARK: - UIDocumentInteractionViewController delegate methods
    
    func documentInteractionControllerViewControllerForPreview(controller: UIDocumentInteractionController) -> UIViewController {
        return self
    }
    

    }

    Call downloadFileForfileObject() in viewDidLoad method with your pdf url as a parameter. The pdf will be automatically shown by UIDocumentInteractionController delegate method.

    SWIFT 3:

    import UIKit
    
    class MOViewController:UIViewController, UIDocumentInteractionControllerDelegate {
    
    var documentController: UIDocumentInteractionController = UIDocumentInteractionController()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        downloadFileForfileObject(url: "https://d0.awsstatic.com/whitepapers/KMS-Cryptographic-Details.pdf")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    
    }
    
    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 teask = session.dataTask(with: request) { (data, response, error) in
            if (error == nil) {
                // Success
                self.openSelectedDocumentFromURL(documentURLString: fileURLPath!.path)
            } else {
                print(error?.localizedDescription)
            }
        }
        teask.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
    
    func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
        return self
    }
    

    Document download verification: You check whether document is downloading or not by follows, see image.

    Output:

    Thanks:)

提交回复
热议问题