WKWebView实践分享

自从公司的ezbuy App最低支持版本提高到iOS8之后, 使用更多的iOS8之后才特有的新特性就被提上了议程, 好比WebKit. 做为公司最没有节操, 最没有底线的程序员之一, 这项任务不可避免的就落到了个人身上.前端

既然要使用Webkit, 那么首先咱们就得明白为何要使用它, 它相对于UIWebView来讲, 有什么优点, 同时, 还得知道它的劣势,以及这些劣势是否会对公司现有业务形成影响.程序员

首先咱们来讲说它的优点:web

  • 性能更高 高达60fps的滚动刷新以及内置手势
  • 内存占用更低 内存占用只有UIWebView的1/4左右
  • 容许JavaScript的Nitro库的加载并使用
  • 支持更多的HtML5特性
  • 原生支持加载进度
  • 支持自定义UserAgent(iOS9以上)

再来讲说它的劣势:swift

  • 不支持缓存
  • 不能拦截修改Request

说完了优点劣势, 那下面就来讲说它的基本用法.api

1、加载网页

加载网页的方法和UIWebView相同, 代码以下:缓存

let webView = WKWebView(frame: self.view.bounds,configuration: config)
webView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
view.addSubview(webView)
复制代码
2、WKWebView的代理方法

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)
复制代码

WKUIDelegatedom

// 建立一个新的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里面相应的代理方法挪过来而已.

3、WKWebView的Cookie

因为咱们的APP内使用了大量的商品列表/活动等H5页面, H5须要知道是哪个用户在访问这个页面, 那么用Cookie是最好也是最合适的解决方案了, 在UIWebView的时候, 咱们并无使用Cookie的困扰, 咱们只须要写一个方法, 往HTTPCookieStorage里面注入一个咱们用户的HTTPCookie就能够了.同一个应用,不一样UIWebView之间的Cookie是自动同步的。而且能够被其余网络类访问好比NSURLConnection,AFNetworking

它们都是保存在HTTPCookieStorage容器中。 当UIWebView加载一个URL的时候,在加载完成时候,Http Response,对Cookie进行写入,更新或者删除,结果更新CookieHTTPCookieStorage存储容器中。 代码相似于:

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,因此不能访问WKWebViewCookie,现象就是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)
    }
复制代码
4、关于User-Agent

上面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])
        })
    }
复制代码
5、关于国际化

解决了上面的问题, 我们产品经理又提出了国际化的需求, 由于咱们的APP同时为至少5个国家的客户提供, 国际化的方案也是我作的, APP内部能够热切换语言, 也许在下一篇博文中会介绍咱们项目中的国际化方案. 那么请求H5页面的时候, 理所应当的就应该带上语言信息了.

这部分的内容, 由于双十一临近, 目前尚未具体实施. 等功能上线之后, 再来补充.

相关文章
相关标签/搜索