JSViewController.swift
9.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
//
// JSViewController.swift
// ParentAssistant
//
// Created by 葛建军 on 2018/3/17.
// Copyright © 2018年 HANGZHOUTEAM. All rights reserved.
//
import UIKit
import WebKit
class JSViewController: UIViewController,WKUIDelegate,WKScriptMessageHandler,UIActionSheetDelegate,WKNavigationDelegate {
var wkWebView:WKWebView!
var ary:[String]=[]
var jsAry:[String]=[]
var webURL:String!
@IBOutlet var progressView: UIProgressView!
@IBOutlet var closeMenu: UIBarButtonItem!
@IBOutlet var moreMenu: UIBarButtonItem!
var loadingView:UIView!
var loadingImageWidth:CGFloat = 60
var borderline:Bool = false//web页面有无边框
override func viewDidLoad() {
super.viewDidLoad()
if let url = URL(string: webURL){
}else{
return
}
// js配置
// WKWebView的配置
let configuration=WKWebViewConfiguration()
configuration.userContentController.add(self, name: "onTokenSetup")
configuration.userContentController.add(self, name: "setMenu")
configuration.userContentController.add(self, name: "clearMenu")
// 显示WKWebView
wkWebView=WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: getScreenHeight()-64),configuration: configuration)
// 有web页面要求留边框
var line:CGFloat = 0
if borderline {
line = 16
}
if UIApplication.shared.statusBarFrame.size.height>20 {
wkWebView.frame = CGRect(x: line, y: line, width: self.view.frame.size.width-2*line, height: getScreenHeight()-88-line)
}else{
wkWebView.frame = CGRect(x: line, y: line, width: self.view.frame.size.width-2*line, height: getScreenHeight()-64-line)
}
wkWebView.uiDelegate=self
wkWebView.navigationDelegate=self
self.wkWebView.load(Foundation.URLRequest(url: URL(string: webURL)!))
wkWebView.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.new, context: nil)
wkWebView.addObserver(self, forKeyPath: "title", options: NSKeyValueObservingOptions.new, context: nil)
if ary.count==0 {
self.navigationItem.rightBarButtonItems = [closeMenu]
}
self.view.insertSubview(wkWebView, belowSubview: progressView)
loadingView = UIView(frame: UIScreen.main.bounds)
loadingView.backgroundColor = UIColor.black.withAlphaComponent(0.3)
let loadImage = UIImageView()
loadImage.frame.size = CGSize(width: loadingImageWidth, height: loadingImageWidth)
loadImage.center = CGPoint(x: getScreenWidth()/2, y: getScreenHeight()/2-64-loadingImageWidth/2)
var arr:[UIImage] = []
for i in 0...4 {
let image = UIImage(named: "js_load_icon_\(i+1)")
arr.append(image!)
}
loadImage.animationImages = arr
loadImage.animationDuration = 2
loadingView.addSubview(loadImage)
let label = UILabel()
label.text = "正在拼命加载中..."
label.textColor = UIColor.white
label.sizeToFit()
label.center = CGPoint(x: getScreenWidth()/2, y: getScreenHeight()/2-64+30)
loadingView.addSubview(label)
loadImage.startAnimating()
self.view.insertSubview(loadingView, aboveSubview: progressView)
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
DebugLog( "方法名:\(message.name),参数:\(message.body)")
// 调用方法
if message.name == "setMenu" {
ary=[]
jsAry=[]
let array=message.body as! [NSDictionary]
for item in array {
ary.append((item["title"] as? String)!)
jsAry.append((item["action"] as? String)!)
}
if ary.count>0 {
self.navigationItem.rightBarButtonItems=[moreMenu,closeMenu]
}else{
self.navigationItem.rightBarButtonItems = [closeMenu]
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func closeAction(_ sender: AnyObject) {
navigationController?.dismiss(animated: true, completion: nil)
}
@IBAction func showJSAlert(_ sender: UIBarButtonItem) {
let action=UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil)
for title in ary {
action.addButton(withTitle: title)
}
action.show(in: self.view)
}
func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int) {
for i in 1...ary.count {
if buttonIndex==i {
self.wkWebView.evaluateJavaScript(jsAry[i-1], completionHandler: { (data, error) in
if error != nil {
DebugLog( "错误:\(String(describing: error?.localizedDescription)))")
}
})
}
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath=="estimatedProgress" {
if object as! WKWebView == self.wkWebView {
self.progressView.alpha=1.0
self.progressView.setProgress(Float(wkWebView.estimatedProgress), animated: true)
DebugLog( "+++++++++++++++++\(Float(wkWebView.estimatedProgress))")
if wkWebView.estimatedProgress >= 1.0 {
UIView.animate(withDuration: 0.3, delay: 0.3, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.progressView.alpha=0.0
}, completion: { (finished) in
self.progressView.setProgress(0.0, animated: false)
})
}
}else{
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}else if keyPath=="title" {
if object as! WKWebView == self.wkWebView {
self.navigationItem.title=self.wkWebView.title
}else{
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}else{
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
@IBAction func onBackClicked(_ sender: UIBarButtonItem) {
if wkWebView.canGoBack{
wkWebView.goBack()
}else{
navigationController?.dismiss(animated: true, completion: nil)
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
if webView.title! != "身份验证..." {
loadingView.removeFromSuperview()
}
if webURL.contains("gettoken") {
let token = AccountManager.shared.loadToken()?["access_token"].stringValue ?? "0"
webView.evaluateJavaScript("onTokenSetup(\"\(token)\");", completionHandler: { (str, error) in
if error==nil {
}else{
}
})
}
}
func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
completionHandler()
let alert=UIAlertController(title: "提示",message: "\(message)",preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "cancel", style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
completionHandler(false)
}
func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
completionHandler(nil)
}
// func webView(webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: (Bool) -> Void) {
// let token = AccountManager.shared.loadToken()?["access_token"].stringValue ?? "0"
// webView.evaluateJavaScript("onTokenSetup(\"\(token)\");", completionHandler: { (str, error) in
// if error==nil {
//
// }else{
// showAlertView((error?.description)!)
// }
// })
// self.navigationItem.title = webView.title
// }
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}