1.iOS12 之前 使用 UIWebView
1>
private lazy var webV : UIWebView = {
let v = UIWebView(frame: self.view.bounds)
let url = URL(string: "https://www.baidu.com/")
v.delegate = self
if let url = url {
let urlRequest = URLRequest(url: url)
v.loadRequest(urlRequest)
}
return v
}()
2>
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(webV)
}
3>
extension ViewController:UIWebViewDelegate{
}
2. iOS 12 之后 系统推荐WKWebView 替代 UIWebView
1>
private lazy var wkWebV: WKWebView = {
let config = WKWebViewConfiguration()
// 设置偏好设置
config.preferences = WKPreferences()
// // 默认为0
// config.preferences.minimumFontSize = 10
// 默认认为YES
config.preferences.javaScriptEnabled = true
// 在iOS上默认为NO,表示不能自动通过窗口打开
config.preferences.javaScriptCanOpenWindowsAutomatically = false
// web内容处理池,由于没有属性可以设置,也没有方法可以调用,不用手动创建
config.processPool = WKProcessPool()
// 通过JS与webview内容交互
config.userContentController = WKUserContentController()
// 注入JS对象名称AppModel,当JS通过AppModel来调用时,
// 我们可以在WKScriptMessageHandler代理中接收到
// config.userContentController.add(self, name: "AppModel")
let url = URL(string: "https://www.baidu.com/")
let web = WKWebView(frame: view.bounds, configuration: config)
web.navigationDelegate = self
web.uiDelegate = self
if let url = url {
let urlRequest = URLRequest(url: url)
web.load(urlRequest)
}
return web
}()
2>
view.addSubview(wkWebV)
3.
extension ViewController:WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler{
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
}
}