移動應用中許多複雜的且常常改動的頁面會使用H5進行代替native,這裏就會使用到js和webview的交互web
iOS裏面,UIWebView提供了方法stringByEvaluatingJavaScriptFromString:使js和webview互通函數
這裏我提供一種思路,僅供參考lua
1.加載js函數url
var Test = {}; Test.platform = { name: 'IOS' }; // 返回App識別ID Test.getAppId = function(){ return '[AppId]'; }; // 返回用戶Id Test.getUserId = function(){ return '[UserId]'; }; // 返回當前AppVersion Test.getAppVersion = function(){ return '[AppVersion]'; }; Test.open = function(str){ setTimeout(function(){ document.location = 'Test://open/'+str; },50); }; window.Test = Test;
2.簡單幾個函數,加載前替換掉本身的value,component
for (NSString *key in dict) { NSString *placekey = [NSString stringWithFormat:@"[%@]", key]; NSString *value = [dict[key] stringValue]; if (! value || [value isEqual:[NSNull null]]) { jsString = [jsString stringByReplacingOccurrencesOfString:placekey withString:@"null"]; }else{ jsString = [jsString stringByReplacingOccurrencesOfString:placekey withString:value]; } }
3.加入webview的js裏面:orm
[webView stringByEvaluatingJavaScriptFromString:jsString];
當js調用native的操做時候,能夠使用Test.open(firstViewController?paramter=123)
native的delegate將會調用:blog
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
這裏的request.url將會是:ip
Test://open/firstViewController?paramter=123
進入咱們本身解析方法,對此url進行不一樣的解析和跳轉ci
NSString *requestString = [[request URL] absoluteString]; NSArray *components = [requestString componentsSeparatedByString:@"://"]; if (components[0] && [components count] > 1) {//若是協議擡頭爲Test或者爲其餘則走自定義流程 NSString *content = components[1]; NSArray *controller = [content componentsSeparatedByString:@"/"]; if (controller.count > 1 && [controller[0] isEqual:@"open"]) {//打開特定的controller [self openController:controller[1]]; } } return NO;