* * * * * * * * * * * * * * * * * * * * * * * * * *
I recently learned a bit about customizing WKWebView, In this paper, the content filtering rules of WKWebView (WKContentRuleList) and the way WKWebView loads photos in the album to display them in WKWebView (WKURLSchemeHandler) will be mainly explained.
WKContentRuleList make-https
WKContentRuleList is a list of compilation rules applied to Web content. It is suitable for iOS11.0+ devices. We can give the webView. Configuration. Add WKContentRuleList userContentController, make the webView to load abide by the rules.
- The make-https of WKContentRuleList can change the HTTP URL to HTTPS. Urls with specified (non-default) ports and links using other protocols are not affected.
For example, we want to access www.so.com, but write www.so.com in the URL, and www.so.com can be accessed normally. If ATS is not configured, If make-https is configured, webViews in the application will also load properly.
Note: if the other URL we want to visit is www.xxx.com and the URL is written as www.xxx.com, the WebView will not load properly if xxx.com does not support HTTPS. Thanks Xs·H and dac_1033 for correcting and providing a command to verify whether the url currently accessed supports HTTPS. The following command output can also be used to configure ATS configuration rules for certain urls in the info. plist file.
nscurl --ats-diagnostics URL
Copy the code
For example: test www.so.com
nscurl --ats-diagnostics http://so.com
Starting ATS Diagnostics
Configuring ATS Info.plist keys and displaying the result of HTTPS loads to https://so.com.
A test will "PASS" if URLSession:task:didCompleteWithError: returns a nil error.
Use '--verbose' to view the ATS dictionaries used and to display the error received in URLSession:task:didCompleteWithError:.
================================================================================
Default ATS Secure Connection
---
ATS Default Connection
Result : PASS
---
Copy the code
Using make-https is useful for HTTP URL configuration only when Result has Pass, as in the example above.
Add RuleList code to iOS 11.0+ :
- (void)configMakeHttps {
// Provide ContentRule rules
NSArray *jsonArr =
@[@{
@"trigger": @ {// Matches all urls with a regular expression value
@"url-filter": @ ". *"
},
@"action": @ {// Set the type to make- HTTPS for the URL
@"type": @"make-https"}},]; [self compileContentRuleWithJsonArray:jsonArr];
}
Copy the code
- (void)compileContentRuleWithJsonArray:(NSArray *)jsonArr {
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonArr options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// Compile ContentRule rules
[[WKContentRuleListStore defaultStore] compileContentRuleListForIdentifier:@"ContentBlockingRules"
encodedContentRuleList:jsonStr
completionHandler:^(WKContentRuleList *ruleList, NSError *err) {
if (ruleList) {
// Add RuleList to WebView configuration
[self.webView.configuration.userContentController addContentRuleList:ruleList];
NSLog(Compiled ruleList: %@, ruleList);
} else {
NSLog(@" Compiled ruleList is empty, error message: %@", err); }}]; }Copy the code
The request below is converted to a request www.so.com
[_webView loadRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.so.com"]]];
Copy the code
WKContentRuleList block
- Block stops loading resources. If the resource is cached, the cache is ignored.
Block blocks loading a specific URL
Use blocks to block parts of the URL from being displayed properly. The effect of blocking loading a specific image URL is as follows:
The key codes are as follows:
- (void)configBlockURL {
NSArray *jsonArr =
@[
@{
@"trigger": @ {// A specified URL can also be configured to match urls that meet other criteria
@"url-filter": @"(https://upload.jianshu.io/users/upload_avatars/2628633/c6a17aeb-04be-4862-9b2d-01db2a3dd16c.png)",},@"action": @ {@"type": @"block"}},// make HTTP to HTTPS@ {@"trigger": @ {@"url-filter": @ ". *"
},
@"action": @ {@"type": @"make-https"}},]; [self compileContentRuleWithJsonArray:jsonArr];
}
Copy the code
[_webView loadFileURL:[[NSBundle mainBundle] URLForResource:@"QiContentRule" withExtension:@"html"] allowingReadAccessToURL:[[NSBundle mainBundle] bundleURL]];
Copy the code
The qicontentrule.html used by the author is as follows:
<! DOCTYPEhtml>
<html>
<head>
<meta charset="utf-8">
<title>QiWKWebView</title>
</head>
<body>Test load support HTTPS HTTP link pictures of http://upload.jianshu.io/collections/images/1673367/8.png<br>
<img src="http://upload.jianshu.io/collections/images/1673367/8.png? imageMogr2/auto-orient/strip" width="300">
<br>Test block images load https://upload.jianshu.io/users/upload_avatars/2628633/c6a17aeb-04be-4862-9b2d-01db2a3dd16c.png<br>
<! -- <img src="http://p0.qhimg.com/d/QiShare/QiShare.png" width="300" height="300">-->
<br>
<img src="https://upload.jianshu.io/users/upload_avatars/2628633/c6a17aeb-04be-4862-9b2d-01db2a3dd16c.png" alt="Test block picture picture load failed" width="300" height= "300">
<br>
</body>
</html>
Copy the code
Block blocks loading certain resources
The author uses block combined with if-domain (control if it is under a certain domain name) and resource-type (put the image type into the array) to block the access to the image resource of simple book. The effect is as follows:
The relevant codes are as follows:
/ /! The configuration blocks loading of certain resources
- (void)configBlockLoadSomeResource {
NSArray *jsonArr =
@[
/ / block resources@ {@"trigger": @ {@"url-filter": @ ". *".// @"resource-type": @[@"image", @"style-sheet", @"font", @"script", @"document", @"media", @"popup"],
@"resource-type": @ [@"image"].// @"unless-domain": @[@"www.jianshu.com"],
@"if-domain": @ [@"www.jianshu.com"],},@"action": @ {//block:Stops loading of the resource. If the resource was cached, the cache is ignored.
// Stop loading resources. If the resource is cached, the cache is ignored.
@"type": @"block"}}]; [self compileContentRuleWithJsonArray:jsonArr];
}
Copy the code
[_webView loadRequest: [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://www.jianshu.com/u/3db23baa08c7"]]];
Copy the code
For more ContentRule rules see Creating a Content Blocker
WKURLSchemeHandler
WKURLSchemeHandler is the protocol used to load custom URL Schemes such as URL Schemes such as HTTPS that WKWebView can handle. The author made a custom protocol by loading photos in the album back to the WebView Demo.
WKURLSchemeHandler loads the album image echo to WKWebView
The following figure shows the use of WKURLSchemeHandler to control the retrieval of images from an album to the IMG of a WebView. All we need to do is set up WKWebViewConfiguration to set up URLSchemeHandler to handle the object and the URLScheme to handle it. The WKURLSchemeHandler proxy methods of startURLSchemeTask and stopURLSchemeTask are called when the URLScheme we are working with is loaded. We can prepare and provide the corresponding data content to the WebView task in the corresponding proxy method to display the corresponding data.
The relevant code used by the author is as follows:
- (void)loadView {
WKWebViewConfiguration *webConfig = [WKWebViewConfiguration new];
_schemeHandler = [QiCustomSchemeHandler new];
[webConfig setURLSchemeHandler:_schemeHandler forURLScheme:@"qiLocal"];
_webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:webConfig];
_webView.allowsBackForwardNavigationGestures = YES;
_webView.backgroundColor = [UIColor whiteColor];
self.view = _webView;
}
Copy the code
[_webView loadFileURL:[[NSBundle mainBundle] URLForResource:@"QiCustomResource" withExtension:@"html"] allowingReadAccessToURL:[[NSBundle mainBundle] bundleURL]];
Copy the code
- (void)webView:(WKWebView *)webView startURLSchemeTask:(id<WKURLSchemeTask>)urlSchemeTask {
if ([urlSchemeTask.request.URL.absoluteString hasPrefix:@"qilocal://"]) { // qiLocal
dispatch_async(dispatch_get_main_queue(), ^{
self.imageDataBlock = ^(NSData * _Nonnull data, NSURLResponse * _Nonnull response) {
[urlSchemeTask didReceiveResponse:response];
[urlSchemeTask didReceiveData:data];
[urlSchemeTask didFinish];
};
UIImagePickerController *imagePicker = [UIImagePickerController new];
imagePicker.delegate = self.sourceViewController;
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self.sourceViewController showViewController:imagePicker sender:nil];
self.imagePickerController = imagePicker; }); }}Copy the code
QiCustomResource. HTML is as follows:
<! DOCTYPE html> <html> <head> <meta charset="utf-8">
<title>QiWKWebView</title>
</head>
<body>
<a href="qiLocal://locaResource.com" rel="external nofollow" target="_top">QiLocalCustomResource</a>
<br>
<img src="qiLocal://locaResource.com" alt="Get pictures from mobile phone" width="300">
</body>
</html>
Copy the code
Demo
See Demo: QiWKWebView for details
Refer to study website
- Creating a Content Blocker
- WKWebView
- The use of its
- IOS 11: WKWebView content filtering rules in detail
- WKWebView the pit
- New feature for iOS 11 WKWebView
To learn more about iOS and related new technologies, please follow our official account:
You can add the following xiaobian wechat, and note to join the QiShare technical exchange group, xiaobian will invite you to join the QiShare technical Exchange Group.
Ways to focus on us are:
QiShare(GitHub) QiShare(CocoaChina) QiShare(StackOverflow) QiShare(wechat)
Recommended articles:
Swift 5.1 (6) – Function Swift 5.1 (5) – Control flow Xcode11 New project SceneDelegate iOS App startup optimization (II) — Use “Time Profiler” tool to monitor the App startup Time iOS App startup optimization (a) — understand the App startup process iOS WKWebView basic use Swift 5.1 (4) – collection type strange dance weekly