swift 4错误:将html字符串加载到webview

时间:2017-12-08 10:40:35

标签: html swift webview

我尝试在我的网页视图中加载一个html字符串,代码为:

let htmlFile = Bundle.main.path(forResource: "code", ofType: "html")
        let html = try! String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
        self.weview.loadHTMLString(html, baseURL: nil)

我运行应用程序,一切正常,但如果我按下网站链接,我在AppDelegate中收到错误:Thread 1: EXC_BAD_ACCESS (code=1, address=0x10) 有人可以给我一个swift 4的代码,我可以加载一个html字符串并与之交互吗?会非常好。

2 个答案:

答案 0 :(得分:0)

试试这个:

let link = "https://google.co.in"
do {
    let htmlStr = try String(contentsOf : URL(string:link)!)
    let separateHtmlStr = htmlStr.components(separatedBy:"") // any html tag you want to interact with

    let newURL = URL(string: link)
    yourWebView.loadHTMLString(separateHtmlStr, baseURL: newURL) // in case if you have changed anything

   }catch{
        print("Exception")
    }
}

答案 1 :(得分:0)

要检查的第一件事 - 转到Project Settings -> Build Phases -> Copy Bundle Resources以确保您的html文件目录在那里。

其次,按照下面列出的方式加载文件。您不必加载文件的内容。

let path = Bundle.main.path(forResource: "code", ofType: "html")!
let uri = URL(string: path)!
let request = URLRequest(url: uri)
webView.loadRequest(request)

另外,请确保forResource param包含从项目目录开始的html文件的完整路径