Swift: Read pdf file into pdf application reader

后端 未结 2 455
悲哀的现实
悲哀的现实 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:10

    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!)
                      }
                   }
    
                }
    
            }
    
        }
    
    }
    

提交回复
热议问题