1. UIWebView

UIWebView is suitable for iOS8.0 or lower versions of the system. There is no way for javascript to call OC directly. It can only be intercepted by UIWebView’s UIWebViewDelegate protocol method, and in this method, call OC methods according to the URL.

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
Copy the code
  • The UIWebViewDelegate proxy protocol uses:
// Whether to allow loading of web pages, also can get js to open the URL, By intercepting the url can interact with js - (BOOL) webView: (UIWebView *) webView shouldStartLoadWithRequest (NSURLRequest *) request navigationType:(UIWebViewNavigationType)navigationType { NSString *urlString = [[request URL] absoluteString]; urlString = [urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSArray *urlComps = [urlString componentsSeparatedByString:@": / /"];
    NSLog(@"urlString=%@---urlComps=%@",urlString,urlComps);
    returnYES; } // start loading web page - (void)webViewDidStartLoad:(UIWebView *)webView {NSURLRequest *request = webview.request; NSLog(@"webViewDidStartLoad-url=%@--%@",[request URL],[request HTTPBody]); } - (void)webViewDidFinishLoad:(UIWebView *)webView {NSURLRequest *request = webview.request; NSURL *url = [request URL];if ([url.path isEqualToString:@"/normal.html"]) {
        NSLog(@"isEqualToString");
    }
    NSLog(@"webViewDidFinishLoad-url=%@--%@",[request URL],[request HTTPBody]);
    NSLog(@"% @",[self.webView stringByEvaluatingJavaScriptFromString:@"document.title"]); } // web page load error - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {NSURLRequest *request = webView.request; NSLog(@"didFailLoadWithError-url=%@--%@",[request URL],[request HTTPBody]);
}
Copy the code

2. WKWebView

  • The introduction of its library#import <WebKit/WebKit.h>
  • As you can see from the documentation, there are two initialization methods for WKWebView:
- (instancetype)initWithFrame:(CGRect)frame
- (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration
Copy the code

We mostly use the first approach, which is the default in the documentation.

  • The WKWebView proxy protocol is as follows:
/ / start page load when the - (void) webView: (WKWebView *) webView didStartProvisionalNavigation: (null_unspecified WKNavigation *)navigation { NSLog(@"Called when the page starts loading. 2. ""); } // when the content is returned, - (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation { NSLog(@"Called when the content is returned, called when the requested content is retrieved. 4"); } // call - (void)webView (WKWebView *)webView didFinishNavigation (WKNavigation *)navigation {NSLog(@"Called when the page has finished loading. 5. ""); } / / request failed calls - (void) webView: (WKWebView *) webView didFailProvisionalNavigation navigation: (WKNavigation *) withError:(NSError *)error { NSLog(@"error1:%@",error);
}
-(void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    NSLog(@"error2:%@",error); } // Before the request is sent, decide whether to jump -> If this method is not implemented, the system defaults to jump. If this method is implemented, you need to enable the jump. If this method is not set, an error is reported. //Terminating app due to uncaught exception'NSInternalInconsistencyException', reason: 'Completion handler passed to -[ViewController webView:decidePolicyForNavigationAction:decisionHandler:] was not called'- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction DecisionHandler :(void (^)(WKNavigationActionPolicy))decisionHandler decisionHandler(WKNavigationActionPolicyAllow); / / is not allowed to jump / / decisionHandler (WKNavigationActionPolicyCancel); NSLog(@"Before the request is sent, decide whether to jump. 1"); } // After receiving the response, Deciding whether to jump (ditto) / / implementation of this method in the content before returning - (void) webView: (WKWebView *) webView decidePolicyForNavigationResponse: (WKNavigationResponse *) navigationResponse decisionHandler: (void) (^) (WKNavigationResponsePolicy) decisionHandler {/ / allowed to jump decisionHandler(WKNavigationResponsePolicyAllow); / / is not allowed to jump / / decisionHandler (WKNavigationResponsePolicyCancel); NSLog(@"After receiving the response, decide whether to jump. 3"); } // call - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation { NSLog(@"Called when a server jump request is received");
}
-(void)webViewWebContentProcessDidTerminate:(WKWebView *)webView
{
    NSLog(@"webViewWebContentProcessDidTerminate");
}
Copy the code

3. OC calls JS to pass parameters

  • UIWebView method
NSString *str = [self.webview stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"postStr('%@','%@');",str1,str2]];
Copy the code
  • WKWebView method
[self.wkWebView evaluateJavaScript:[NSString stringWithFormat:@"postStr('%@')"The @"true"] completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSLog(@"= = % @ % @", result, error);
    }];
Copy the code

Implement the following method in the JS interface that needs to accept parameter values:

functionpostStr(str1, str2){ alert(str1, str2); // Received value "; / /... code }Copy the code

4. JS calls OC to pass arguments

Js cannot execute OC code, but it can be executed in a disguised way. Js can encapsulate the operation to be executed in the network request, and then OC intercepts the request to obtain the string parsing in the URL. (Intercepting urls) such as Darkangel ://. The method is that in HTML or JS, when a button is clicked to trigger an event, the link formed by the custom URL Scheme will be jumped, and the link will be captured in OC, and the necessary parameters will be parsed from it to achieve an interaction between JS and OC. SMS authentication login

  • UIWebView method
The return value of the /* * method is BOOL. * Returns YES: tells the browser to do the default action, such as a link jump * returns NO: It means that the default operation of the browser is not performed. Here, it is determined that the native operation of JS is performed by the URL protocol, which is definitely not the default operation of the browser. It returns NO * / - (BOOL) webView: (UIWebView *) webView shouldStartLoadWithRequest (NSURLRequest *) request NavigationType (UIWebViewNavigationType)navigationType{// The standard URL contains scheme, host, port, path, query, fragment, etc. NSURL *URL = request.URL;if ([URL.scheme isEqualToString:@"darkangel"]) {
        if ([URL.host isEqualToString:@"smsLogin"]) {
            NSLog(@"SMS verification code login, parameter is %@", URL.query);
            returnNO; }}return YES;
}
Copy the code
  • WKWebView method
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction DecisionHandler (void (^) (WKNavigationActionPolicy)) decisionHandler {/ / by navigationAction navigationType jump type, Such as new links, such as backward NSURL. * URL = navigationAction. The request URL. // Check whether the URL complies with the user-defined URL Schemeif ([URL.scheme isEqualToString:@"darkangel"]) {// Perform corresponding operations and obtain parameters according to different servicesif ([URL.host isEqualToString:@"smsLogin"]) {
            NSString *param = URL.query;
            NSLog(@"SMS verification code login, parameter is %@", param); / / do not allow the jump decisionHandler (WKNavigationActionPolicyCancel);return; }} / / allowed to jump decisionHandler (WKNavigationActionPolicyAllow); NSLog(@"% @", NSStringFromSelector(_cmd));
}
Copy the code

Attached: my blog address