UIWebView

It is used in the same way as normal View. There is a built-in UIScrollView.

You need to set the UIWebViewDelegate. Delegate has only four callback methods: Start, load starts, Load completes, and load fails.

HTML

[webView loadHTMLString:@"<html><body><p>this is baidu!</p></body></html>" baseURL:];
Copy the code

HTML File

NSString *str = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
NSURL *url = [NSURL fileURLWithPath:str];
[webView loadFileURL:url allowingReadAccessToURL:url];
Copy the code

NSData

NSString *path = [[NSBundle mainBundle] pathForResource:@"demo" ofType:@"gif"];
NSData *data = [NSData dataWithContentsOfFile:path];
[webView loadData:data MIMEType:@"image/gif" textEncodingName:@"UTF-8" baseURL:url];
webView.userInteractionEnabled = NO;
Copy the code

Set MIMEType to the specified type

@"image/jpg"
@"image/gif"
@"application/pdf"
Copy the code

URLRequest

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[webView loadRequest:request];
Copy the code

UIWebViewDelegate

/ / if the load - (BOOL) webView: (UIWebView *) webView shouldStartLoadWithRequest (NSURLRequest *) request navigationType:(UIWebViewNavigationType)navigationType { NSLog(@">>>>>>>>>> %s", __FUNCTION__); return YES; } / / the load - (void) webViewDidStartLoad: (UIWebView *) webView {NSLog (@ "> > > > > > > > > > % s", __FUNCTION__); } / / the load complete - (void) webViewDidFinishLoad: (UIWebView *) webView {NSLog (@ "> > > > > > > > > > % s", __FUNCTION__); } // load failed - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {NSLog(@">>>>>>>>>> %s", __FUNCTION__); }Copy the code

keywords

  1. The App occupies memory. If the memory consumption is too large, the App may crash.
  2. It is not as flexible as WKWebView and provides few delegate callback methods.

WKWebView

Load HTML, NSData is consistent with UIWebView.

Independent process, network loading and UI rendering allows multiple processes simultaneously, similar to Chrome. So the App’s memory consumption drops dramatically, while the memory consumption of other processes increases.

If the memory consumption is too high, UIWebView will cause app to be killed, while WKWebView’s Web Content process will be killed and a blank screen will appear.

There’s WKNavigationDelegate and WKUIDelegate.

Alert popups: WKUIDelegate runJavaScriptAlertPanelWithMessage method of the agreement.

Confirm the pop-up: WKUIDelegate runJavaScriptConfirmPanelWithMessage method of the agreement.

WKWebViewConfiguration

Use WKWebView’s default initialization method:

- (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration;
Copy the code

The system copies the Configuration object. Modifying the Configuration object does not take effect.

WKNavigationDelegate

Customize the behavior of a webView to accept, load, complete requests, and so on.

  • The WKNavigation object contains information to track the page loading process.
  • The WKNavigationAction object contains information about the actions that might lead to a load for making policy decisions.
  • The WKNavigationResponse object contains the browse response information used to make policy decisions

The key, unlike UIWebView, is:

/*! A class conforming to the WKNavigationDelegate protocol can provide
 methods for tracking progress for main frame navigations and for deciding
 policy for main frame and subframe navigations.
 */

// MARK: 拦截URL

/*! @abstract Decides whether to allow or cancel a navigation.
 @param webView The web view invoking the delegate method.
 @param navigationAction Descriptive information about the action
 triggering the navigation request.
 @param decisionHandler The decision handler to call to allow or cancel the
 navigation. The argument is one of the constants of the enumerated type WKNavigationActionPolicy.
 @discussion If you do not implement this method, the web view will load the request or, if appropriate, forward it to another application.
 */
// 接收到响应后, 如何处理(是否跳转, 是否拦截URL等)
// 调用decisionHandler(WKNavigationActionPolicyAllow);则允许跳转
// 调用decisionHandler(WKNavigationActionPolicyCancel);即不允许跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSLog(@">>>>>>>>>> %s", __FUNCTION__);
    // 该方法实现了, 则必须调用decisionHandler.
    
    NSURL *url = navigationAction.request.URL;
    
    if ([url.absoluteString isEqualToString:@"about:blank"]) {
        decisionHandler(WKNavigationActionPolicyAllow);
        return;
    }
    
    NSString *scheme = [url scheme];
    
    NSURL *docUrl = navigationAction.request.mainDocumentURL;
    NSURL *urlOfBundleFilePrefix = [docUrl URLByDeletingLastPathComponent];
    NSString *route = [url.absoluteString stringByReplacingOccurrencesOfString:urlOfBundleFilePrefix.absoluteString withString:@""];
    
    
    if ([route containsString:@"actionOC_JS://"]) {
        [self routeJS_OC_Action:route];
        
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    
    NSString *host = [url host];
    
    NSLog(@"comes from %@ %@", scheme, host);
    
    if ([host containsString:@"baidu"]) {
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    
    decisionHandler(WKNavigationActionPolicyAllow);
}

/*! @abstract Decides whether to allow or cancel a navigation after its
 response is known.
 @param webView The web view invoking the delegate method.
 @param navigationResponse Descriptive information about the navigation
 response.
 @param decisionHandler The decision handler to call to allow or cancel the
 navigation. The argument is one of the constants of the enumerated type WKNavigationResponsePolicy.
 @discussion If you do not implement this method, the web view will allow the response, if the web view can show it.
 */
//- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
//    NSLog(@">>>>>>>>>> %s", __FUNCTION__);
//}

/*! @abstract Invoked when a main frame navigation starts.
 @param webView The web view invoking the delegate method.
 @param navigation The navigation.
 */
// 页面开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
    NSLog(@">>>>>>>>>> %s", __FUNCTION__);
}

/*! @abstract Invoked when a server redirect is received for the main
 frame.
 @param webView The web view invoking the delegate method.
 @param navigation The navigation.
 */
// 接收到服务器的重定向
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
    NSLog(@">>>>>>>>>> %s", __FUNCTION__);
}

/*! @abstract Invoked when an error occurs while starting to load data for
 the main frame.
 @param webView The web view invoking the delegate method.
 @param navigation The navigation.
 @param error The error that occurred.
 */
// 页面加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@">>>>>>>>>> %s", __FUNCTION__);
    NSLog(@"error: %@", error);
}

/*! @abstract Invoked when content starts arriving for the main frame.
 @param webView The web view invoking the delegate method.
 @param navigation The navigation.
 */
// 跳转已经完成, 页面内容开始到达并展示
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation {
    NSLog(@">>>>>>>>>> %s", __FUNCTION__);
}

/*! @abstract Invoked when a main frame navigation completes.
 @param webView The web view invoking the delegate method.
 @param navigation The navigation.
 */
// 页面跳转完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    NSLog(@">>>>>>>>>> %s", __FUNCTION__);
}

/*! @abstract Invoked when an error occurs during a committed main frame
 navigation.
 @param webView The web view invoking the delegate method.
 @param navigation The navigation.
 @param error The error that occurred.
 */
// 页面跳转失败
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@">>>>>>>>>> %s", __FUNCTION__);
}

/*! @abstract Invoked when the web view needs to respond to an authentication challenge.
 @param webView The web view that received the authentication challenge.
 @param challenge The authentication challenge.
 @param completionHandler The completion handler you must invoke to respond to the challenge. The
 disposition argument is one of the constants of the enumerated type
 NSURLSessionAuthChallengeDisposition. When disposition is NSURLSessionAuthChallengeUseCredential,
 the credential argument is the credential to use, or nil to indicate continuing without a
 credential.
 @discussion If you do not implement this method, the web view will respond to the authentication challenge with the NSURLSessionAuthChallengeRejectProtectionSpace disposition.
 */
//- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler {
//    NSLog(@">>>>>>>>>> %s", __FUNCTION__);
//}

/*
 这个方法比较关键,web content process因内存消耗过大被杀死,则此回调会触发。在其中可以对webView进行reload操作。
*/
/*! @abstract Invoked when the web view's web content process is terminated.
 @param webView The web view whose underlying web content process was terminated.
 */
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
    NSLog(@">>>>>>>>>> %s", __FUNCTION__);
}
Copy the code

Among them:

/ * * in decidePolicyForNavigationAction approach, according to some parameters of navigationAction, resolve the corresponding action and parameters, execution. For these actions: if some interface of iOS is called, over. If I prepare some arguments and pass them to a function in JS, */ - (void)routeJS_OC_Action:(NSString *)route {NSString *action = [route stringByReplacingOccurrencesOfString:@"actionOC_JS://" withString:@""]; if ([action containsString:@"setColor"]) { NSString *paramStr = [action stringByReplacingOccurrencesOfString:@"setColor?" withString:@""]; NSArray *params = [paramStr componentsSeparatedByString:@"&"]; NSMutableDictionary *colorDic = [NSMutableDictionary dictionary]; for (NSString *colorStr in params) { NSArray *key_value = [colorStr componentsSeparatedByString:@"="]; [colorDic setObject:key_value[1] forKey:key_value[0]]; } CGFloat r = [[colorDic objectForKey:@"r"] floatValue]; CGFloat g = [[colorDic objectForKey:@"g"] floatValue]; CGFloat b = [[colorDic objectForKey:@"b"] floatValue]; CGFloat a = [[colorDic objectForKey:@"a"] floatValue]; UIColor *color = [UIColor colorWithRed: R /255.0 green: G /255.0 blue: B /255.0 alpha:a]; [self p_actionSetColor:color]; } else if ([action containsString:@"getLocation"]) { [self p_actionGetLocation]; } else if ([action containsString:@"share"]) { [self p_actionShare]; } else if ([action containsString:@"scan"]) { } else if ([action containsString:@"shake"]) { } else if ([action containsString:@"pay"]) { } }Copy the code

WKUIDelegate

Provides methods for presenting native user interfaces to web pages. The WebView user interface implements this protocol to control the opening of new Windows, enhance the appearance of the default menu items displayed when the user clicks on an element, and perform other user interface related tasks. These methods can be invoked by processing JavaScript or other plug-in content. By default, there is one window per WebView. If you need to implement an unconventional user interface, you need to rely on WKUIDelegate to implement it.

The key, unlike UIWebView, is:

/*! A class conforming to the WKUIDelegate protocol provides methods for
 presenting native UI on behalf of a webpage.
 */

/*! @abstract Creates a new web view.
 @param webView The web view invoking the delegate method.
 @param configuration The configuration to use when creating the new web
 view.
 @param navigationAction The navigation action causing the new web view to
 be created.
 @param windowFeatures Window features requested by the webpage.
 @result A new web view or nil.
 @discussion The web view returned must be created with the specified configuration. WebKit will load the request in the returned web view.
 
 If you do not implement this method, the web view will cancel the navigation.
 */
//- (nullable WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures;

/*! @abstract Notifies your app that the DOM window object's close() method completed successfully.
 @param webView The web view invoking the delegate method.
 @discussion Your app should remove the web view from the view hierarchy and update
 the UI as needed, such as by closing the containing browser tab or window.
 */
- (void)webViewDidClose:(WKWebView *)webView {
    NSLog(@">>>>>>>>>> %s", __FUNCTION__);
}

/*! @abstract Displays a JavaScript alert panel.
 @param webView The web view invoking the delegate method.
 @param message The message to display.
 @param frame Information about the frame whose JavaScript initiated this
 call.
 @param completionHandler The completion handler to call after the alert
 panel has been dismissed.
 @discussion For user security, your app should call attention to the fact
 that a specific website controls the content in this panel. A simple forumla
 for identifying the controlling website is frame.request.URL.host.
 The panel should have a single OK button.
 
 If you do not implement this method, the web view will behave as if the user selected the OK button.
 */
// 弹出警告框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    NSLog(@">>>>>>>>>> %s", __FUNCTION__);
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Alert" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
}

/*! @abstract Displays a JavaScript confirm panel.
 @param webView The web view invoking the delegate method.
 @param message The message to display.
 @param frame Information about the frame whose JavaScript initiated this call.
 @param completionHandler The completion handler to call after the confirm
 panel has been dismissed. Pass YES if the user chose OK, NO if the user
 chose Cancel.
 @discussion For user security, your app should call attention to the fact
 that a specific website controls the content in this panel. A simple forumla
 for identifying the controlling website is frame.request.URL.host.
 The panel should have two buttons, such as OK and Cancel.
 
 If you do not implement this method, the web view will behave as if the user selected the Cancel button.
 */
// 弹出确认框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler {
    NSLog(@">>>>>>>>>> %s", __FUNCTION__);
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Confirm" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
}

/*! @abstract Displays a JavaScript text input panel.
 @param webView The web view invoking the delegate method.
 @param message The message to display.
 @param defaultText The initial text to display in the text entry field.
 @param frame Information about the frame whose JavaScript initiated this call.
 @param completionHandler The completion handler to call after the text
 input panel has been dismissed. Pass the entered text if the user chose
 OK, otherwise nil.
 @discussion For user security, your app should call attention to the fact
 that a specific website controls the content in this panel. A simple forumla
 for identifying the controlling website is frame.request.URL.host.
 The panel should have two buttons, such as OK and Cancel, and a field in
 which to enter text.
 
 If you do not implement this method, the web view will behave as if the user selected the Cancel button.
 */
// 弹出输入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable result))completionHandler {
    NSLog(@">>>>>>>>>> %s", __FUNCTION__);
}

#if TARGET_OS_IPHONE

/*! @abstract Allows your app to determine whether or not the given element should show a preview.
 @param webView The web view invoking the delegate method.
 @param elementInfo The elementInfo for the element the user has started touching.
 @discussion To disable previews entirely for the given element, return NO. Returning NO will prevent
 webView:previewingViewControllerForElement:defaultActions: and webView:commitPreviewingViewController:
 from being invoked.
 
 This method will only be invoked for elements that have default preview in WebKit, which is
 limited to links. In the future, it could be invoked for additional elements.
 */
// 是否预览
- (BOOL)webView:(WKWebView *)webView shouldPreviewElement:(WKPreviewElementInfo *)elementInfo {
    NSLog(@">>>>>>>>>> %s", __FUNCTION__);
    return YES;
}

/*! @abstract Allows your app to provide a custom view controller to show when the given element is peeked.
 @param webView The web view invoking the delegate method.
 @param elementInfo The elementInfo for the element the user is peeking.
 @param defaultActions An array of the actions that WebKit would use as previewActionItems for this element by
 default. These actions would be used if allowsLinkPreview is YES but these delegate methods have not been
 implemented, or if this delegate method returns nil.
 @discussion Returning a view controller will result in that view controller being displayed as a peek preview.
 To use the defaultActions, your app is responsible for returning whichever of those actions it wants in your
 view controller's implementation of -previewActionItems.
 
 Returning nil will result in WebKit's default preview behavior. webView:commitPreviewingViewController: will only be invoked
 if a non-nil view controller was returned.
 */
//- (nullable UIViewController *)webView:(WKWebView *)webView previewingViewControllerForElement:(WKPreviewElementInfo *)elementInfo defaultActions:(NSArray<id <WKPreviewActionItem>> *)previewActions API_AVAILABLE(ios(10.0))

/*! @abstract Allows your app to pop to the view controller it created.
 @param webView The web view invoking the delegate method.
 @param previewingViewController The view controller that is being popped.
 */
- (void)webView:(WKWebView *)webView commitPreviewingViewController:(UIViewController *)previewingViewController {
    NSLog(@">>>>>>>>>> %s", __FUNCTION__);
}

#endif // TARGET_OS_IPHONE

#if !TARGET_OS_IPHONE

/*! @abstract Displays a file upload panel.
 @param webView The web view invoking the delegate method.
 @param parameters Parameters describing the file upload control.
 @param frame Information about the frame whose file upload control initiated this call.
 @param completionHandler The completion handler to call after open panel has been dismissed. Pass the selected URLs if the user chose OK, otherwise nil.
 
 If you do not implement this method, the web view will behave as if the user selected the Cancel button.
 */
//- (void)webView:(WKWebView *)webView runOpenPanelWithParameters:(WKOpenPanelParameters *)parameters initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSArray<NSURL *> * _Nullable URLs))completionHandler API_AVAILABLE(macosx(10.12));

#endif
Copy the code

keywords

  1. It’s much more granular than UIWebView. After the server requests a response, it asks whether to load the content into the current WKWebView. UIWebView is directly loaded. When the URL content has been downloaded, it will ask if the downloaded content is allowed to load.
  2. With a redirection notification, the WKWebView process exits with a terminate callback method.
  3. It does not occupy the App’s own memory. But the memory of the Web Content Process introduces problems such as a blank screen.
  4. Views such as Alert and Conform need to receive notifications through the WKUIDelegate protocol, which is implemented natively in iOS.
  5. Native->JS communication, WKWebView is asynchronous, while UIWebView is synchronous.
  6. The cookie mechanism is complicated.

Some properties of KVO are supported:

  1. title
  2. URL
  3. estimatedProgress
  4. HasOnlySecureContent, are all resources on the page loaded through secure links?
  5. loading

Title, URL, and loading can be used to check whether loading is successful, for example, whether a webView is blank.

How to debug a WebView

Enter the corresponding WebView interface of iOS simulator, open Safari, and open the development menu. Note that the App does not need to be in debugging when debugging.

To Debug the WebView on the iOS real machine, set Safari > Advanced > Open JavaScript and Web inspector, and use the Debug certificate.

WKHTTPCookieStore

Objects that manage HTTP cookies associated with a specific WKWebsiteDataStore:

- (void)getAllCookies:(void (^)(NSArray<NSHTTPCookie *> *))completionHandler;
- (void)setCookie:(NSHTTPCookie *)cookie completionHandler:(void (^)(void))completionHandler;
- (void)deleteCookie:(NSHTTPCookie *)cookie completionHandler:(void (^)(void))completionHandler;
- (void)addObserver:(id<WKHTTPCookieStoreObserver>)observer;
- (void)removeObserver:(id<WKHTTPCookieStoreObserver>)observer;
- (void)cookiesDidChangeInCookieStore:(WKHTTPCookieStore *)cookieStore;
Copy the code

Note that cookies can be used for monitoring.

JavaScriptCore

Similar to Google’s V8 engine, JSCore is the core engine for interpreting executing JavaScript code.

JSVirtualMachine, JSContext, JSValue, JSExport, evaluateJavaScript.

The following are all one-to-many:

JS VM ---> JSContext ---> JSValue
Copy the code

JSVirtualMachine

Provides a virtual machine environment for JS code to run. A JS VM can execute only one thread. To multithread, you need to create multiple JS VMS. What is the relationship with the single threaded model of JS?

Each JS VM has its own GC and objects cannot be passed between multiple JS VMS.

JSContext

Is the context of the JS runtime environment, responsible for Native and JS data transfer

JSValue

JS value object, which provides the conversion mode between JS original value object and Native object.

Native->JS

[webView evaluateJavaScript:jsString]
Copy the code

or

[jsContext evaluateScript:jsString];
Copy the code

Use toString, toNumber, and toDictionary to fetch the corresponding Native object from JSValue.

To use a JS function object, use the callWithArguments method:

[context evaluateString:@"function addition(x,y) {return x+ y}"];
JSValue *addition = context[@"addition"];
JSValue *resultValue = [addition callWithArguments:@[@(4), @(8)]];
[resultValue toNumber];
Copy the code

Similar to that in Weex:

- (JSValue *)callJSMethod:(NSString *)method args:(NSArray *)args {
    return [[_jsContext globalObject] invokeMethod:method withArguments:args];
}
Copy the code

JS->Native

Using block:

context[@"subtraction"] = ^(int x, int y) { return x + y; } JSValue *subValue = [context evaluateScript:@"subtraction(4,8);"] ; [subValue toNumber];Copy the code

JS calls Native code via block or closure.

JSExport

JSExport protocol, which can export Native objects to JSContext.

A custom protocol inherits the JSExport protocol, passing OC objects into JS.

@protocol PersonJSExport <JSExport> @end jsContext[@"Person"] = [Person class]; [jsContext evaluateScript:@"var personWithName = function(name) { var person = Person.persionWithName(name);  return person; }"]; [[jsContext objectForKeyedSubscript:@"persionWithName"] callWithArguments:@[@"Chris"]];Copy the code

Here, the OC class Person inherits the JSExport protocol, and then wraps a function personWithName to call the initialization code for the OC class. Retrieve the JS function via objectForKeyedSubscript and execute it using callWithArguments:.

JSPatch principle

In addition to block and JSExport, dynamic calls can be implemented using JSContext and JSValue type conversions and OC Runtime message forwarding mechanism, avoiding the JSExport protocol, the implementation principle of JSPatch.

The composition of JavaScriptCore

A real JavaScript virtual machine containing an interpreter and runtime.

The interpreter compiles high-level scripting languages into bytecode, and runtime manages runtime memory space.

JSCore internally consists of Parse, Interpreter, Compiler, and GC.

Explain to perform

Parser conducts lexical analysis, syntax analysis and bytecode generation.

Interpreter Performs the interpretation. First LLInt (Low Level Interpreter) executes the bytecode generated by Parser, and JSCore optimizes functions or loops that are run frequently.

Optimizers include Baseline JIT, DFG JIT, FTL JIT, etc.

Executing JS code

- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^)(id, NSError *error))completionHandler;
Copy the code

Notice that its completionHandler is executed on the main thread.

Other Key points

WKProcessPool

Process pool for Web Content. When the WKWebView object is initialized, a Web Content process object is retrieved from the process pool.

screenshots

- (void)takeSnapshotWithConfiguration:(WKSnapshotConfiguration *)snapshotConfiguration completionHandler:(void (^)(UIImage *snapshotImage, NSError *error))completionHandler;
Copy the code

You can customize the webView screenshot area using WKSnapshotConfiguration.

WKUserContentController

Provides methods for sending JS messages to WKWebView or injecting JS scripts.

A WKUserScript object represents a script that can be injected into a web page. Script injection timing, can only be set by WKUserScriptInjectionTime enumeration. It contains WKUserScriptInjectionTimeAtDocumentStart and WKUserScriptInjectionTimeAtDocumentEnd.

WKScriptMessageHandler

Classes that implement this protocol can receive JS invocation methods from web pages.

The WKScriptMessage object contains information about a JS message. The attribute ID body can only be an object type.

WKWebsiteDataStore

If a WebView is associated with a non-persistent WKWebsiteDataStore, no data will be written to the file system. This feature can be used for private browsing. You can also set the traceless mode by setting configuration.

A WKWebsiteDataStore object represents the various types of data used by web pages. This includes cookies, disk files, in-memory caches and persistent data such as WebSQL, IndexedDB databases, and local storage.

WKURLSchemeHandler

Used to handle URL Scheme-type resources that WebKit cannot handle

Used when loading a specific resource.

- (void)webView:(WKWebView *)webView startURLSchemeTask:(id<WKURLSchemeTask>)urlSchemeTask;
- (void)webView:(WKWebView *)webView stopURLSchemeTask:(id<WKURLSchemeTask>)urlSchemeTask;
Copy the code

WKURLSchemeTask is the task used to load the resource.

Common routines for WKWebView

Use KVO to monitor load progress

[webView addObserver:self forKeyPath:@"loading" options:NSKeyValueObservingOptionNew context:nil];
[webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
Copy the code
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:@"loading"]) { NSLog(@"loading: %d", _webView.isLoading); } else if ([keyPath isEqualToString:@"estimatedProgress"]) { NSLog(@"estimatedProgress: %f", _webView.estimatedProgress); self.progressView.progress = _webView.estimatedProgress; if (self.progressView.progress >= 1.f) { self.progressView.progress = 0.f; }}}Copy the code

View all cookies

webView.configuration.websiteDataStore.httpCookieStore.getAllCookies { cookies in
    for cookie in cookies {
        if cookie.name == "authentication" {
            self.webView.configuration.websiteDataStore.httpCookieStore.delete(cookie)
        } else {
            print("\(cookie.name) is set to \(cookie.value)")}}}Copy the code

Causes and handling measures of blank screen

See the previous blog WKWebView for more details.

The resources

  • Teach you the correct posture to use WKWebView
  • WKWebView,
  • IOS Development Master class