文章目录
准备
添加权限
使得除了https的网站也能在iOS中运行起来
import
import WebKit
设置根视图
var webView: WKWebView!
override func loadView() {
let config = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: config)
webView.allowsBackForwardNavigationGestures = true
webView.uiDelegate = self
webView.navigationDelegate = self //就是LoadDelegate
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
webView.load("https://www.google.com")
}
在另个WKWebView.swift里面
import UIKit
import WebKit
extension WKWebView {
func load(_ string: String) {
if let url = URL(string: string) {
load(URLRequest(url: url))
}
}
}
一些方法
var webView: WKWebView!
//用于判断
webView.isLoading
webView.canGoBack
webView.canGoForward
//方法
webView.reload()
webView.reloadFromOrigin()
webView.stopLoading()
webView.goBack()
webView.goForward()
设置JS的三个弹出框为iOS原生alert
首先遵循协议
extension ViewController: WKUIDelegate {
}
alert() 警告框
extension ViewController: WKUIDelegate {
func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .default, handler: {
(_) in
completionHandler()
}))
present(alert, animated: true, completion: nil)
}
}
confirm() 确认框
extension ViewController: WKUIDelegate {
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {