Js與OC互動

來源:互聯網
上載者:User

標籤:

Js與OC互動

源碼請點擊github地址下載。

下面講述實現OC和JS的互動,它們相互調用,其中需要寫一個靜態HTML檔案用於提供JS方法。

如下:
screen.png一.OC調用JS:

不說閑話,看代碼如下

  • 需要先在js檔案定義方法postStr供oc調用
    function postStr(string) {      return ‘I am the return parameter JS, and param ‘ + string; }
  • oc代碼只需一句即可調用
  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‘;"];}
  • 用於js統計
- (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互動

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.