iOS與JS互動

來源:互聯網
上載者:User

標籤:blog   ber   代碼   x11   val   elf   原理   等於   pen   

① iOS -> JS

原理:通過WebView的方法直接調用JS代碼

[WebView stringByEvaluatingJavaScriptFromString:@"A"];

// 這裡的 A 就是WebView中的html所對應的JS代碼

eg.

1)這裡一個html所包含的js檔案內的一個public方法

2)這是一個.m(iOS)檔案內的一個WebView的調用1)中js方法的寫法

3)那麼在js的對應方法中,就會得到來自iOS的參數

 

② JS -> iOS

原理:iOS端的WebView的協議函數回調可以擷取到其內部html元素的變化以及相應值,JS端只需變化內部元素即可

步驟一:JS端的處理

步驟二:JS端添加子項目後iOS端的回調

WebView   -   UIWebViewDelegate

- (BOOL)webView:(UIWebView *)theWebView shouldStartLoadWithRequest:(NSMutableURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{

   //擷取JS端元素變化後的請求字串(得到BC?D=d)

  NSString *reqString = [[[request URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

  // B 可以作為判斷Flag

  // C 是調用的iOS的方法名稱

  // ? 為分隔字元

  // D 為參數名稱

  // = 就是等號,沒啥意思

  // d 為具體參數(請以json格式傳輸,因為iOS的SEL的參數限制)

 

  // 得到了方法名以及參數之後得到SEL對象

  SEL sel = NSSelectorFromString([methodName stringByAppendingString:@":"]);

  // 也可以得到參數string to dictionary

  NSData *jsonData = [C dataUsingEncoding:NSUTF8StringEncoding];    NSError *err;    NSDictionary *argsInfo = [NSJSONSerialization JSONObjectWithData:jsonData                                                        options:NSJSONReadingMutableContainers                                                          error:&err];  // 方法有了,參數也有了,調用,參數是以dictionary的形式給出的  

  if ([self respondsToSelector:sel]) {

    // 調用方法C,參數為一個字典(iOS中的方法C的參數也應當為dictionary)

          [self performSelector:sel withObject:argsInfo];  

      }

} 

 

iOS與JS互動

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.