无法访问捆绑包中的文件

时间:2017-10-18 20:47:39

标签: ios swift pdf bundle

我在捆绑中获取文件的路径/网址时遇到问题。这是我使用的代码

@IBOutlet weak var testWebView: UIWebView!

private func setText() {

if let path = Bundle.main.path(forResource: "theory", ofType: "pdf") {
    let url = NSURL(fileURLWithPath: path)
    let request = NSURLRequest(url: url as URL)
    testWebView.loadRequest(request as URLRequest)
 }
}
override func viewDidLoad() {
   super.viewDidLoad()
  // setText()
}

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
setText()
}

文件理论.pdf在主包中(没有子文件夹等) 我尝试了很多方法,比如使用Create Group / Create folder Reference等进行复制 - 没有任何帮助。 webView在StoryBoard中设置。

2 个答案:

答案 0 :(得分:0)

如果您的目标是展示PDF,我强烈建议您使用UIDocumentInteractionController

class ViewController: UIViewController {

    private var documentInteractionController: UIDocumentInteractionController?

    private func setText() {
        if let path = Bundle.main.path(forResource: "theory", ofType: "pdf") {
            let url = URL(fileURLWithPath: path)
            let controller = UIDocumentInteractionController(url: url)
            controller.delegate = self
            controller.presentPreview(animated: true)
            documentInteractionController = controller
        }
    }

    override func viewDidAppear(_ animated: Bool) {
         super.viewDidAppear(animated)
         setText()
    }

}

您还需要实施UIDocumentInteractionControllerDelegate

extension ViewController: UIDocumentInteractionControllerDelegate {

    func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
         return self
    }

}

答案 1 :(得分:0)

谢谢大家。我解决了这个问题。我没有将PDF拖放到包中,而是右键单击Project Navigator并选择将文件添加到... 此后再次右键单击上传的文件,然后选择添加.... 最后它奏效了。再次感谢。现在我将尝试你的提议。