在ios11中,WKWebview增加了三个API对应三个新特性:
WKHTTPCookieStore:管理cookie
WKContentRuleList:过滤掉不想要的内容
WKURLSchemeHandler:用于处理自定义的 URL Scheme
WKHTTPCookieStore:
开发者可以添加或移除某一个cookie;可以获取一个WKWebView实例里所有的cookie。
1.首先从实例里获取一个cookieStore:
open class WKWebsiteDataStore : NSObject, NSCoding {
open var httpCookieStore: WKHTTPCookieStore { get }
}
let cookieStore = webView.configuration.websiteDataStore.httpCookieStore;
2.添加一个cookie:
let cookie = HTTPCookie(properties: [
HTTPCookiePropertyKey.domain: "canineschool.org",
HTTPCookiePropertyKey.path: "/",
HTTPCookiePropertyKey.secure: true,
HTTPCookiePropertyKey.name: "LoginSessionID",
HTTPCookiePropertyKey.value: "5bd9d8cabc46041579a311230539b8d1"])
cookieStore.setCookie(cookie!) {
webView.load(loggedInURLRequest)
}
3.获取实例里所有的cookie:
cookieStore.getAllCookies() { (cookies) in
for cookie in cookies {
// Find the login cookie
}
}
4.删除一个cookie:
cookieStore.delete(cookie!) {
webView.load(loggedOutURLRequest)
}
WKContentRuleList:
内容过滤器,基于在ios9中新增的Content Blocker功能,将他应用在了WKWebView中,可实现屏蔽符合自定义过滤规则的资源内容,屏蔽cookie,将http转换为https等。
WebKit在编译这些规则时使用的是比较高效的bytecode。
1.json格式的过滤规则示例(将连接转换为https):
[{
"trigger": {
"url-filter": ".*"
},
"action": {
"type": "make-https"
}
}]
2.编译这个规则:
let jsonString = loadJSONFromBundle()
WKContentRuleListStore.default().compileContentRuleList(
forIdentifier: "ContentBlockingRules",
encodedContentRuleList: jsonString) { (contentRuleList, error) in
if let error = error {
return
}
createWebViewWithContentRuleList(ruleList!)
}
3.进入这个预先编译好的过滤规则:
WKContentRuleListStore.default().lookUpContentRuleList(forIdentifier: "ContentBlockingRules") {
(contentRuleList, error) in
// Use previously compiled content rule list
}
4.将规则应用到某个WKWebView实例:
let configuration = WKWebViewConfiguration()
configuration.userContentController.add(contentRuleList)
WKURLSchemeHandler:
可以给你指定的某些Scheme,如https,file,mailto添加一些handler语句,在请求这些scheme时加一些自己的处理内容。
有一个Scheme作为苹果的预留,你不能使用:"local",建议改为"apple-local"之类的。
1.自定义一个handler,包含加载URL开始跟结束的回调:
class MyCustomSchemeHandler : NSObject, WKURLSchemeHandler {
func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) {
}
func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) {
}
}
2.为WK的实例设置这个handler:
let configuration = WKWebViewConfiguration()
configuration.setURLSchemeHandler(MyCustomSchemeHandler(), forURLScheme: “apple-local”)
3.在开始回调里指定需要的数据:
func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) {
let resourceData = createHTMLResourceData()
let response = URLResponse(
url: urlSchemeTask.request.url!,
mimeType: “text/html”,
expectedContentLength: resourceData.count,
textEncodingName: nil)
}
4.将数据返回:
func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) {
let resourceData = createHTMLResourceData()
let response = ...
urlSchemeTask.didReceive(response)
urlSchemeTask.didReceive(resourceData)
urlSchemeTask.didFinish()
}
网友评论