// 1.新建WebView self.webView = [[UIWebView alloc] initWithFrame:self.view.bounds]; [self.view addSubview:self.webView]; // 2.加载网页 NSString *indexPath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]; NSString *appHtml = [NSString stringWithContentsOfFile:indexPath encoding:NSUTF8StringEncoding error:nil]; NSURL *baseUrl = [NSURL fileURLWithPath:indexPath]; [self.webView loadHTMLString:appHtml baseURL:baseUrl]; // 3.开启日志 [GCWebviewJSBridge setEnableLogging]; // 4.给webView建立JS和OC的沟通桥梁 _bridge = [GCWebviewJSBridge bridgeForWebView:self.webView]; [_bridge setwebViewDelegate:self];
JS的准备工作
之前是只写一套, 发现iOS行了Android又不行了; Android行了iOS又不行了. 最后才知道需要写两套
// 这段代码是固定的,必须要放到js中 function setupWebViewJavascriptBridge(callback) { //Android if (window.GCWebviewAndroidJSBridge) { callback(GCWebviewAndroidJSBridge) } else { document.addEventListener( ‘GCWebviewAndroidJSBridgeReady‘ , function() { callback(GCWebviewAndroidJSBridge) }, false ); } //iOS if (window.GCWebviewJSBridge) { return callback(GCWebviewJSBridge); } if (window.KBWVJSBCallBacks) { return window.KBWVJSBCallBacks.push(callback); } window.KBWVJSBCallBacks = [callback]; var GCWVJSBIframe = document.createElement(‘iframe‘); GCWVJSBIframe.style.display = ‘none‘; GCWVJSBIframe.src = ‘gcwvjsbscheme://__GC_BRIDGE_LOADED__‘; document.documentElement.appendChild(GCWVJSBIframe); setTimeout(function() { document.documentElement.removeChild(GCWVJSBIframe) }, 0); }
- 一. iOS注册方法提供给JS调用
- iOS注册访问相册方法
[_bridge registerObjCHandler:@"openCamera" handler:^(id data, GCWVJSBResponseCallback responseCallback) { NSLog(@"需要%@图片", data[@"count"]); UIImagePickerController *imageVC = [[UIImagePickerController alloc] init]; imageVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; [self presentViewController:imageVC animated:YES completion:nil]; }];
JS调用该方法的代码片段
- JS调用打开相册方法
bridge.callHandler(‘openCamera‘, {‘count‘:‘10张‘}, function responseCallback(responseData) { console.log("OC中返回的参数:", responseData) });
- 二. JS注册方法提供给iOS调用. (oc 调用 js)
- iOS注册提供用户信息方法
/* JS给OC提供公开的API, 在OC中可以手动调用此API, 并且可以接收OC中传过来的参数,同时可回调OC */ // 获取用户信息 bridge.registerHandler(‘getUserInfo‘, function(data, responseCallback) { console.log("OC中传递过来的参数:", data); // 把处理好的结果返回给OC responseCallback({"userID":"DX001", "userName":"旋之华", "age":"18", "otherName":"旋之华"}) });
iOS调用JS中的方法, 获得用户信息
// 调用JS中的API [self.bridge callHandler:@"getUserInfo" data:@{@"userId":@"DX001"} responseCallback:^(id responseData) { NSString *userInfo = [NSString stringWithFormat:@"%@,姓名:%@,年龄:%@", responseData[@"userID"], responseData[@"userName"], responseData[@"age"]]; }];