Ne AS
Ne AS

Reputation: 1550

Swift: Read pdf file into pdf application reader

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 display pdf file. How can I do it with the way that I described?

Edit: I have only the pdf link that I get from the server

Upvotes: 1

Views: 4262

Answers (2)

Binesh
Binesh

Reputation: 61

Try this

var docController:UIDocumentInteractionController!
let pdfUrl = NSURL(string: "ENTER_URL_OF_PDF")

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    downloadDoc(pdfUrl: pdfUrl!)
}

@IBAction func buttonAction(_ sender: AnyObject) {
    docController.presentOptionsMenu(from: self.view.frame, in: self.view, animated: true)
}

func downloadDoc(pdfUrl : NSURL) {
    let urlTest = self.pdfUrl!.absoluteString
    let pdfUrl = NSURL(string: urlTest!)
    if(pdfUrl != nil){
        let pdfRequest: NSURLRequest = NSURLRequest(url: pdfUrl! as URL)
         NSURLConnection.sendAsynchronousRequest(pdfRequest as URLRequest, queue: OperationQueue.main) {(response, data, error) in
            let httpResponse = response as? HTTPURLResponse
            if(httpResponse?.statusCode == 200 && error == nil){
               let documentsUrl =  FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).first as! NSURL

               if let fileName = self.pdfUrl!.lastPathComponent {
                  let destinationUrl = documentsUrl.appendingPathComponent(fileName)
                  if let data = data {
                        do {
                            try data.write(to: destinationUrl!, options: .atomic)
                        } catch {
                            print(error)
                        }
                        self.docController = UIDocumentInteractionController(url: destinationUrl!)
                  }
               }

            }

        }

    }

}

Upvotes: 1

Karthick Selvaraj
Karthick Selvaraj

Reputation: 2505

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.enter image description here

Output:

enter image description here

Thanks:)

Upvotes: 0

Related Questions