如何在没有下载swift的情况下在chrome或safari中打开pdf文件?

时间:2018-06-13 11:13:09

标签: ios swift pdf document

当用户点击pdfButton时,如何在chrome或safari上显示pdf文件。我是iOS和文档显示概念的新手。以下我从服务器获取的数据。

{
  "status" : 200,
  "body" : "<div>Hi Attachment,<\/div><div><br><\/div><div>Attachment Test<br><\/div>",
  "attachment" : "http:\/\/192.168.1.46:3000\/system\/images\/178\/mca%282016-2019%29transfer_certificates_original.pdf?1528805255",
  "sender" : "Dr.P.Shanthi(employee@inmeghcms.in)",
  "message" : "Details fetched successfully",
  "time" : "12 Jun 2018",
  "profile" : "http:\/\/192.168.1.46:3000\/assets\/female.png",
  "subject" : "TEST"
}

2 个答案:

答案 0 :(得分:0)

您可以尝试以下代码,我正在使用@ Binesh代码,我已更新为swift 4.0。

var docController:UIDocumentInteractionController!
    let pdfUrl = NSURL(string: "Use your url")

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

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


func downloadPDfDoc(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!)
                    }
                }

            }

        }

    }

}
}

尝试这个,如果您遇到任何问题,请告诉我。

答案 1 :(得分:0)

如果您有pdf文件的网址,可以使用

在默认网络浏览器中打开它
UIApplication.shared.open(url)