三種加載方式
webView.loadRequest()
webView.loadHTMLString()
webView.loadData()
第一種 加載網(wǎng)絡(luò)鏈接
let url = NSURL(string: "http://ifeng.com")
let request = NSURLRequest(URL: url!)
webView.loadRequest(request)
第二種 加載HTML
let htmlStr = "<h1>這是一個標(biāo)題</h1>"
webView.loadHTMLString(htmlStr, baseURL: nil)
第三種加載本地網(wǎng)頁
//1.
let url = NSBundle.mainBundle().URLForResource("index", withExtension: "html")
let request = NSURLRequest(URL: url!)
webView.loadRequest(request)
//2.
let data = NSData(contentsOfURL: url!)
webView.loadData(data!, MIMEType: "text/html", textEncodingName: "utf-8", baseURL: NSURL())
self.view.addSubview(webView)
加載的時機
//1. 開始加載的時機
//2. 可以過濾網(wǎng)址
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let path = request.URL?.absoluteString
print(path!)
if path!.containsString("baidu.com") {
return false
}
return true
}
func webViewDidStartLoad(webView: UIWebView) {
//
}
func webViewDidFinishLoad(webView: UIWebView) {
//如果需要操作網(wǎng)頁镐作,必須等加載完成
let res = webView.stringByEvaluatingJavaScriptFromString("document.getElementsByTagName('img')")
print(res)
//w3school.com.cn
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者