Swift WKWebView 加载本地文件在设备上不起作用 [英] Swift WKWebView Loading local file not working on a device

查看:27
本文介绍了Swift WKWebView 加载本地文件在设备上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试在 iPad(或任何设备)上运行我的应用程序时遇到了一些问题,它在模拟器上按预期运行,因此它在设备上不起作用很奇怪.我想知道是否有人可以指出我正确的方向.我花了很多时间阅读这里所有其他关于相同问题的帖子,但是没有一个建议的解决方案有效.

I am having some issues when trying to run my app on an iPad (or any device) it runs as expected on the emulator so it is weird that it doesn't work on a device. I was wondering if some one could point me in the correct direction. I spend many hours reading all the other posts on here about the same issues, however none of the suggested solutions worked.

我有一个正在加载本地 html 文件的 WKWebView.在模拟器上加载文件并且一切正常,但在设备上我在日志中收到一条消息:

I have a WKWebView into which I am loading a local html file. On the emulator the file loads and everything works fine but on a device I am getting a message in the log:

无法为/"创建沙箱扩展

Could not create a sandbox extension for '/'

这是我将文件加载到

override func viewDidLoad() {
    super.viewDidLoad()
    var path = NSBundle.mainBundle().pathForResource("Login_UK",
        ofType: "html")
    var url = NSURL(fileURLWithPath: path!)
    var request = NSURLRequest(URL: url!)

    var theConfiguration = WKWebViewConfiguration()
    theConfiguration.userContentController.addScriptMessageHandler(self,
        name: "callbackHandler")

    webView = WKWebView(frame: self.view.frame,
        configuration: theConfiguration)
    webView!.loadRequest(request)
    self.view.addSubview(webView!)
}

任何帮助将不胜感激

亲切的问候,迪米塔尔

推荐答案

感谢任何试图回答我问题的人.我已经发布,这是 Apple 试图修复的 WebKit 库的错误.但是,我找到了一个很好的解决方法,只需要很少的工作.

Thank you for any one who tried to answer my question. I have released that this is an error with the WebKit lib that Apple are trying to fix. However I have found a good workaround that required little work.

我打开本地文件并读取其内容,然后将该字符串发送到编译文件中的 hmtl 的 webView.loadHTMLString 方法中.这样您就可以避免 iOS 无法找到本地文件路径的问题.

I open the local file and read its content and then send that string into a webView.loadHTMLString method that compiles the hmtl that was in the file. That way you avoid the issues with iOS not being able to find the path to the local file.

以下是读取文件然后为遇到相同问题的任何人打开它的示例:

Here is an example of reading a file and then opening it for any one who has the same issues:

    let path2 = NSBundle.mainBundle().pathForResource("index", ofType: "html")
    var text = String(contentsOfFile: path2!, encoding: NSUTF8StringEncoding, error: nil)!

    webView!.loadHTMLString(text, baseURL: url)

亲切的问候,迪米塔尔

这篇关于Swift WKWebView 加载本地文件在设备上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆