Opening a PDF document when clicking a button

2019-01-15 23:12发布

I am trying to create an app for my family restaurant in swift. I currently have a button that you click on that takes you too a webviewer page of our menu. I want to make the menu with in the app so it does not redirect to safari.

Basically what I want to do is click a button and it opens the menu pdf within the app instead safari.

The code that I use too open the PDF in a browser:

    @IBAction func menu(sender: AnyObject) {
    if let url = NSURL(string:"http://nebula.wsimg.com/db5e994c02db104ea89bdf6e59550490?AccessKeyId=895454CA4A1E296ED3E3&disposition=0&alloworigin=1") {
        UIApplication.sharedApplication().openURL(url)
    }

1条回答
该账号已被封号
2楼-- · 2019-01-15 23:49

You can use QLPreviewController to preview your pdf but it needs to be a local resource or downloaded from the web prior to previewing:

Swift 3 or later

import UIKit
import QuickLook

class ViewController: UIViewController, QLPreviewControllerDataSource {
    let preview = QLPreviewController()
    func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
        return 1
    }
    func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
        return Bundle.main.url(forResource: "menu", withExtension: "pdf")!
            as QLPreviewItem
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // set preview data source
        preview.dataSource = self
        // set current item index (only one = 0)
        preview.currentPreviewItemIndex = 0
    }
    @IBAction func showMenu(sender: UIButton) {
        present(preview, animated: true) {
            // code
        }
    }
}
查看更多
登录 后发表回答