標籤:
Js與OC互動
源碼請點擊github地址下載。
下面講述實現OC和JS的互動,它們相互調用,其中需要寫一個靜態HTML檔案用於提供JS方法。
如下:
screen.png一.OC調用JS:
不說閑話,看代碼如下
NSString *str = [self.webView stringByEvaluatingJavaScriptFromString:@"postStr(‘ocToJs‘)"]; //輸出str為I am the return parameter JS, and param ocToJs,正式js中postStr方法的傳回值。
需注意的是正確書寫@"postStr(‘ocToJs‘)"的格式,postStr為js方法,ocToJs是OC傳遞給JS的參數。
二.JS調用OC:
- 在h5頁面添加了了button元素,用於觸發js方法jsCallOCClicked
<button onclick="jsCallOCClicked()"> <h1>jsCallOC</h1></button>
-
在js檔案的jsCallOCClicked()方法中去調用OC的jsCallToOC()方法
function jsCallOCClicked() { window.location.href = "objc://jsCallToOC#param#github地址#param#https://github.com/SoftProgramLX/OcAndJs"; }
說明:
1.“objc://”為自訂的OC識別JS調用的標識
2.“jsCallToOC”為需調用的OC方法
3.“#param#”為自訂的方法與參數或參數與參數的分隔字元
4.“github地址”為js傳遞給OC的第一個參數
5.“https://github.com/SoftProgramLX/OcAndJs”為js傳遞給OC的第二個參數
-
實現OC的jsCallToOC()方法
- (void)jsCallToOC:(NSArray *)params{ dataArr = params; alertV = [[UIAlertView alloc] initWithTitle:@"js已經調用了OC方法" message:@"查看控制台的資訊,點擊取消會再觸發OC調用js" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"確定", nil]; alertV.tag = 9666; [alertV show]; NSLog(@"js調用OC傳回值:%@", params);}
這裡params[0]輸出是github地址,params[1]輸出是https://github.com/SoftProgramLX/OcAndJs
- 關鍵所在
目前JS調用OC的jsCallToOC()方法還不會觸發,當點擊h5頁面的按鈕時只會觸發OC的- (BOOL)webView:(UIWebView )webView shouldStartLoadWithRequest:(NSURLRequest )request navigationType:(UIWebViewNavigationType)navigationType;這個方法。
需在這個方法裡解析request參數的URL值,解析後path的值就是"objc://jsCallToOC#param#github地址#param#https://github.com/SoftProgramLX/OcAndJs",再繼續分解出裡面的方法與參數,然後執行[self performSelector:todoM withObject:params afterDelay:0];代碼才能觸發OC的jsCallToOC()方法。
代碼如下:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{ NSString *path = [[request URL] absoluteString]; if ([[UIDevice currentDevice].systemVersion doubleValue] >= 7.0) { path = [path stringByRemovingPercentEncoding]; }else{ path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; } if ([path hasPrefix:@"ios"]||[path hasPrefix:@"objc"]) { NSString *method = [path substringFromIndex:@"objc://".length]; NSArray *sels = [method componentsSeparatedByString:@"#param#"]; SEL todoM; if (sels.count>1) { todoM = NSSelectorFromString([NSString stringWithFormat:@"%@:",sels[0]]); NSMutableArray *params = [NSMutableArray array]; for (int i=1; i<sels.count; i++) { [params addObject:sels[i]]; } if ([self respondsToSelector:todoM]) { [self performSelector:todoM withObject:params afterDelay:0]; } }else if(sels.count==1){ todoM = NSSelectorFromString([NSString stringWithString:sels[0]]); if ([self respondsToSelector:todoM]) { [self performSelector:todoM withObject:nil afterDelay:0]; } } return NO; } return YES;}
說明:<br>這裡判斷sels.count>1的目的是判斷有無傳參<br>若無參數則定義方法- (void)jsCallToOC;<br>若有參數則定義方法- (void)jsCallToOC:(NSArray *)params。
三.額外方法
- (void)deletePrompt{ [self.webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect=‘none‘;"]; [self.webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout=‘none‘;"];}
- (void)jsStatistics{ NSString *systemUserAgent = [self.webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"]; if (!([systemUserAgent rangeOfString:@"****-app-iphone Version/"].length > 0)) { NSString *currentVersion = [NSBundle mainBundle].infoDictionary[(__bridge NSString *)kCFBundleVersionKey]; systemUserAgent = [systemUserAgent stringByAppendingFormat:@" ***-app-iphone Version/%@", currentVersion]; } NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:systemUserAgent, @"UserAgent", nil]; [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];}
QQ:2239344645
Js與OC互動