自从公司的ezbuy
App最低支持版本提高到iOS8
之后, 使用更多的iOS8
之后才特有的新特性就被提上了议程, 好比WebKit
. 做为公司最没有节操, 最没有底线的程序员之一, 这项任务不可避免的就落到了个人身上.前端
既然要使用Webkit
, 那么首先咱们就得明白为何要使用它, 它相对于UIWebView
来讲, 有什么优点, 同时, 还得知道它的劣势,以及这些劣势是否会对公司现有业务形成影响.程序员
首先咱们来讲说它的优点:web
iOS9
以上)再来讲说它的劣势:swift
说完了优点劣势, 那下面就来讲说它的基本用法.api
加载网页的方法和UIWebView
相同, 代码以下:缓存
let webView = WKWebView(frame: self.view.bounds,configuration: config)
webView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
view.addSubview(webView)
复制代码
WKNavigationDelegate
服务器
用来追踪加载过程(页面开始加载、加载完成、加载失败)的方法:cookie
// 页面开始加载时调用
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!)
// 当内容开始返回时调用
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!)
// 页面加载完成以后调用
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)
// 页面加载失败时调用
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error)
复制代码
用来跳转页面的方法:网络
// 接收到服务器跳转请求以后调用
func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!)
// 在收到响应后,决定是否跳转
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void)
// 在发送请求以前,决定是否跳转
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
复制代码
WKUIDelegate
dom
// 建立一个新的webView
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView?
// webView中的确认弹窗
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void)
// webView中的输入框
func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void)
// webView中的警告弹窗
func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void)
//TODO: iOS10中新添加的几个代理方法待补充
复制代码
WKScriptMessageHandler
这个协议包含一个必须实现的方法, 它能够直接将接收到的JS脚本转为Swift或者OC对象.
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage)
复制代码
这部分其实除了iOS10新加的几个代理方法, 其余的并无什么特别的. 只不过把本来UIWebView
里面相应的代理方法挪过来而已.
因为咱们的APP内使用了大量的商品列表/活动等H5页面, H5须要知道是哪个用户在访问这个页面, 那么用Cookie
是最好也是最合适的解决方案了, 在UIWebView的时候, 咱们并无使用Cookie
的困扰, 咱们只须要写一个方法, 往HTTPCookieStorage
里面注入一个咱们用户的HTTPCookie
就能够了.同一个应用,不一样UIWebView
之间的Cookie
是自动同步的。而且能够被其余网络类访问好比NSURLConnection
,AFNetworking
。
它们都是保存在HTTPCookieStorage
容器中。 当UIWebView
加载一个URL的时候,在加载完成时候,Http Response,对Cookie
进行写入,更新或者删除,结果更新Cookie
到HTTPCookieStorage
存储容器中。 代码相似于:
public class func updateCurrentCookieIfNeeded() {
let cookieForWeb: HTTPCookie?
if let customer = CustomerUser.current {
var cookie1Props: [HTTPCookiePropertyKey: Any] = [:]
cookie1Props[HTTPCookiePropertyKey.domain] = customer.area?.webURLSource.webCookieHost
cookie1Props[HTTPCookiePropertyKey.path] = "/"
cookie1Props[HTTPCookiePropertyKey.name] = CustomerUser.CookieName
cookie1Props[HTTPCookiePropertyKey.value] = customer.cookie
cookieForWeb = HTTPCookie(properties: cookie1Props)
} else {
cookieForWeb = nil
}
let storage = HTTPCookieStorage.shared
if let cookie = cookieForWeb, let cookie65 = cookieFor65daigou(customer: CustomerUser.current) {
storage.setCookie(cookie)
storage.setCookie(cookie65)
} else {
guard let cookies = storage.cookies else { return }
let needDeleteCookies = cookies.filter { $0.name == CustomerUser.CookieName }
needDeleteCookies.forEach({ (cookie) in
storage.deleteCookie(cookie)
})
}
}
复制代码
可是在我迁移到WKWebView
的时候, 我发现这一招无论用了, WKWebView
实例不会把Cookie
存入到App标准的的Cookie
容器(HTTPCookieStorage
)中, WKWebView
拥有本身的私有存储.
由于 NSURLSession
/NSURLConnection
等网络请求使用HTTPCookieStorage
进行访问Cookie
,因此不能访问WKWebView
的Cookie
,现象就是WKWebView
存了Cookie
,其余的网络类如NSURLSession
/NSURLConnection
却看不到. 同时WKWebView
也不会读取存储在HTTPCookieStorage
中的Cookie
.
为了解决这一问题, 我查了大量的资料, 最后发现经过JS的方式注入Cookie
是对于咱们目前的代码来讲是最合适也是最方便的. 由于咱们已经有了注入到HTTPCookieStorage
的代码, 那么只须要把这些Cookie
转化成JS而且注入到WKWebView
里面就能够了.
fileprivate class func getJSCookiesString(_ cookies: [HTTPCookie]) -> String {
var result = ""
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = "EEE, d MMM yyyy HH:mm:ss zzz"
for cookie in cookies {
result += "document.cookie='\(cookie.name)=\(cookie.value); domain=\(cookie.domain); path=\(cookie.path); "
if let date = cookie.expiresDate {
result += "expires=\(dateFormatter.string(from: date)); "
}
if (cookie.isSecure) {
result += "secure; "
}
result += "'; "
}
return result
}
复制代码
注入的方法就是在每次initWkWebView
的时候, 使用下面的config
就能够了:
public class func wkWebViewConfig() -> WKWebViewConfiguration {
updateCurrentCookieIfNeeded()
let userContentController = WKUserContentController()
if let cookies = HTTPCookieStorage.shared.cookies {
let script = getJSCookiesString(cookies)
let cookieScript = WKUserScript(source: script, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: false)
userContentController.addUserScript(cookieScript)
}
let webViewConfig = WKWebViewConfiguration()
webViewConfig.userContentController = userContentController
return webViewConfig
}
public class func getJSCookiesString() -> String? {
guard let cookies = HTTPCookieStorage.shared.cookies else {
return nil
}
return getJSCookiesString(cookies)
}
复制代码
上面Cookie
的问题解决了, 我们的前端又提出了新的问题, 他们须要知道用户访问了网页是使用了客户端(iOS/Android)来的.
这个就好解决了, 其实和WKWebVIew
的关系不大. 最合适添加的地方就是在User-Agent
里面, 不过并无使用WKWebView本身的User-Agent
去定义, 由于这个字段只支持iOS9
以上, 因此用下面的代码全局添加就能够.
fileprivate func setUserAgent(_ webView: WKWebView) {
let userAgentHasPrefix = "xxxxxx "
webView.evaluateJavaScript("navigator.userAgent", completionHandler: { (result, error) in
guard let agent = result as? String , agent.hasPrefix(userAgentHasPrefix) == false else { return }
let newAgent = userAgentHasPrefix + agent
UserDefaults.standard.register(defaults: ["UserAgent":newAgent])
})
}
复制代码
解决了上面的问题, 我们产品经理又提出了国际化的需求, 由于咱们的APP同时为至少5个国家的客户提供, 国际化的方案也是我作的, APP内部能够热切换语言, 也许在下一篇博文中会介绍咱们项目中的国际化方案.
那么请求H5页面的时候, 理所应当的就应该带上语言信息了.
这部分的内容, 由于双十一临近, 目前尚未具体实施. 等功能上线之后, 再来补充.