Interaction between OC and JS and between OCJS
Currently, APP development is not limited to native development. Many are native + html5 hybrid development.
We can use the webView control to achieve hybrid development.
1. First you need to create an html page
<Html>
Load this page during app Initialization
- (void)viewDidLoad { [super viewDidLoad]; [self.webView loadRequest:[NSURLRequest requestWithURL:[[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"]]];}
2. Implement the UIWebViewDelegate Protocol
Using the stringByEvaluationgJavaScriptFromString protocol method,
Can complete OC call JS
#pragma mark - <UIWebViewDelegate>- (void)webViewDidFinishLoad:(UIWebView *)webView { [webView stringByEvaluatingJavaScriptFromString:@"alert(100)"];}
3.
ShouldStartLoadWithRequest can be used to call OC in JS.
/*** Call OC using this method * third-party framework: WebViewJavaScriptBridge */-(BOOL) webView :( UIWebView *) webView shouldStartLoadWithRequest :( NSURLRequest *) request navigationType :( UIWebViewNavigationType) navigationType {// url = ddz: // sendMessage _? 200 NSString * url = request. URL. absoluteString; NSString * scheme = @ "ddz: //"; if ([url hasPrefix: @ "ddz: //"]) {NSLog (@ "method to call OC"); // obtain the path after the Protocol = sendMessage _? 200 NSString * path = [url substringFromIndex: scheme. length]; // use? Cutting NSArray * subpaths = [path componentsSeparatedByString :@"? "]; // Method name methodName = sendMessage: NSString * methodName = [[subpaths firstObject] stringByReplacingOccurrencesOfString: @" _ "withString: @": "]; // parameter params = 200 NSString * params = [subpaths lastObject]; [self defined mselector: NSSelectorFromString (methodName) withObject: params]; // NSLog (@ "% @", subpaths); return NO;} NSLog (@ "to load other requests, not to call the OC method"); return YES ;}
4.
On github also found a kind of interaction between oc and js class, you can look at the https://github.com/marcuswestin/WebViewJavascriptBridge