import UIKit
import WebKit
import JavaScriptCore
let DeviceWidth = UIScreen.main.bounds.width
let DeviceHeight = UIScreen.main.bounds.height
class WkWebViewController: UIViewController,WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler {
var webUrl:String?
var titleName:String? = ""
override func viewDidLoad() {
super.viewDidLoad()
self.setNav()
// 1醇滥、進(jìn)入網(wǎng)頁
// self.webUrl = "http://www.baidu.com"
// 查看彈出框
// self.webUrl = "http://evt.tiancity.com/csol2/1565/home/index.php"
// 事件交互
self.webUrl = "https://testm.modai.cc/Activity/AnniversaryAward.aspx#url=app"
// self.webUrl = "https://www.apple.com"
// self.webUrl = "http://192.168.0.160:8089/Activity/riskEntrance"
self.view.addSubview(self.wkwebView)
self.wkwebView.addSubview(self.progressView)
self.wkwebView.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.new, context: nil)
}
func setNav() {
self.title = titleName
// 適應(yīng)導(dǎo)航
self.automaticallyAdjustsScrollViewInsets = true
let leftBtns = UIBarButtonItem(image: UIImage.init(named: "back")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal), style: .plain, target: self, action: #selector(backToOneVC))
self.navigationItem.leftBarButtonItem = leftBtns
}
@objc func backToOneVC() {
if self.wkwebView.canGoBack {
self.wkwebView.goBack()
}else{
self.navigationController?.popViewController(animated: true)
}
}
lazy var configuration: WKWebViewConfiguration = {
let config = WKWebViewConfiguration()
// 設(shè)置偏好設(shè)置
config.preferences = WKPreferences()
// 默認(rèn)為0
config.preferences.minimumFontSize = 10
// 默認(rèn)認(rèn)為YES
config.preferences.javaScriptEnabled = true
// 在iOS上默認(rèn)為NO片吊,表示不能自動通過窗口打開
config.preferences.javaScriptCanOpenWindowsAutomatically = false
// web內(nèi)容處理池
config.processPool = WKProcessPool()
// 通過JS與webview內(nèi)容交互
config.userContentController = WKUserContentController()
// 注入JS對象名稱AppModel换团,當(dāng)JS通過AppModel來調(diào)用時凡怎,
// // 我們可以在WKScriptMessageHandler代理中接收到
// config.userContentController.add(self, name: "AwardBuy")
return config
}()
lazy var wkwebView: WKWebView = {
//獲取導(dǎo)航欄高度
let navHeight = self.navigationController?.navigationBar.frame.height
//獲取狀態(tài)欄高度
let statusHeight = UIApplication.shared.statusBarFrame.height
let wkwebview = WKWebView(frame: CGRect(x: 0, y: navHeight!+statusHeight, width: DeviceWidth, height: DeviceHeight-(navHeight!+statusHeight)), configuration: self.configuration)
wkwebview.uiDelegate = self
wkwebview.navigationDelegate = self
wkwebview.allowsBackForwardNavigationGestures = true
wkwebview.load(NSURLRequest(url: URL(string: self.webUrl!)!) as URLRequest)
return wkwebview
}()
lazy var progressView : UIProgressView = {
let pp = UIProgressView.init(frame: CGRect.init(x: 0, y: 0, width: view.frame.size.width, height: 2))
pp.progress = 0.0
pp.tintColor = UIColor.red
// pp.backgroundColor = UIColor.lightGray
// pp.transform = CGAffineTransform.init(scaleX: 1, y: 1)
return pp
}()
// js的提示框事件
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: "Ok", style: .default, handler: { () -> Void in
completionHandler()
}))
self.present(alert, animated: true, completion: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "estimatedProgress" {
self.progressView.alpha = 1.0
progressView.setProgress(Float(self.wkwebView.estimatedProgress), animated: true)
//進(jìn)度條的值最大為1.0
if(self.wkwebView.estimatedProgress >= 1.0) {
UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseInOut, animations: {
self.progressView.alpha = 0.0
}) { (finish:Bool) in
self.progressView.progress = 0
}
}
}
}
func webView( webView: WKWebView, didFinish navigation: WKNavigation!) {
self.wkwebView.evaluateJavaScript("AwardBuy", completionHandler: {(any,error) in
print("111111---------AwardBuy-------------")
if error != nil{
print("---------AwardBuy-------------")
}
})
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print("點(diǎn)擊h5 返回=====\(message)")
if message.name == "AwardBuy" {
let dict = message.body as! NSDictionary
let values = dict["tag"]
print(values ?? "000")
if let a = values {
let b:Int = a as! Int
print("進(jìn)入判斷===\(a)")
if b == 4 {//收藏
self.collectAction(dict: dict)
}else if b == 3 {//分享
}else if b == 1 {//支付
}
}
}else{
print("點(diǎn)擊h5 其他函數(shù)=====\(message)")
}
}
func collectAction(dict:NSDictionary) {
let alert = UIAlertController(title: "溫馨提示", message: "收藏成功", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "知道了", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}