OC與JS的互動,OCJS互動
現在APP的開發已經不局限於原生開發,很多都是原生+html5這種混合開發
我們可以通過webView這個控制項,實現混合開發。
1.首先你需要建立一個html頁面
<html> <head> <meta charset="utf-8"> <title>第一個頁面</title> </head> <script> function login() { location.href = 'ddz://call_?200'; } </script> <body> <button style="background: blue; width:100px; height:30px" onclick="login()">確定</button> <br> <a href="http://www.baidu.com">百度</a> </body></html>
在app初始化時,載入這個頁面
- (void)viewDidLoad { [super viewDidLoad]; [self.webView loadRequest:[NSURLRequest requestWithURL:[[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"]]];}
2.實現UIWebViewDelegate這個協議
利用stringByEvaluationgJavaScriptFromString這個協議方法,
可以完成OC調用JS
#pragma mark - <UIWebViewDelegate>- (void)webViewDidFinishLoad:(UIWebView *)webView { [webView stringByEvaluatingJavaScriptFromString:@"alert(100)"];}
3.
利用shouldStartLoadWithRequest這個方法可以完成JS調用OC
/** * 通過這個方法完成JS調用OC * 第三方架構 :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(@"調用OC的方法"); //獲得協議後面的路徑 path = sendMessage_?200 NSString *path = [url substringFromIndex:scheme.length]; //利用?進行切割 NSArray *subpaths = [path componentsSeparatedByString:@"?"]; //方法名 methodName = sendMessage: NSString *methodName = [[subpaths firstObject] stringByReplacingOccurrencesOfString:@"_" withString:@":"]; //參數 params = 200 NSString *params = [subpaths lastObject]; [self performSelector:NSSelectorFromString(methodName) withObject:params];// NSLog(@"%@",subpaths); return NO; } NSLog(@"想載入其他請求,不是想調用OC的方法"); return YES;}
4.
在github上也找到了一個 oc 和 js 之間能夠互動的類,可以看一下 https://github.com/marcuswestin/WebViewJavascriptBridge