OC與JS互相調用

最近項目中要用到html5來實現,涉及到OC調用JS,以及JS調用OC的方法,這裏把遇到的問題以及實現方法介紹一下。



  1. //  

  2. //  ViewController.h  

  3. //  OC_And_JS  

  4. //  

  5. //  Created by 張傑 on 15/7/9.  

  6. //  Copyright  2015年 張傑. All rights reserved.  

  7. //  

  8.   

  9. #import <UIKit/UIKit.h>  

  10.   

  11. @interface ViewController : UIViewController <UIWebViewDelegate>  

  12.   

  13. @property (weak, nonatomic) IBOutlet UIButton *oc_call_js_no_params;  

  14. @property (weak, nonatomic) IBOutlet UIButton *oc_call_js_has_params;  

  15. @property (weak, nonatomic) IBOutlet UIWebView *mWebView;  

  16. @property (weak, nonatomic) IBOutlet UILabel *js_call_oc_show;  

  17.   

  18. - (IBAction)ocCallJsNoParams:(id)sender;  

  19. - (IBAction)ocCallJsHasParams:(id)sender;  

  20.   

  21.   

  22. @end  



[objc] view plain copy

  1. //  

  2. //  ViewController.m  

  3. //  OC_And_JS  

  4. //  

  5. //  Created by 張傑 on 15/7/9.  

  6. //  Copyright  2015年 張傑. All rights reserved.  

  7. //  

  8.   

  9. #import "ViewController.h"  

  10.   

  11. @interface ViewController ()  

  12.   

  13. @end  

  14.   

  15. @implementation ViewController  

  16.   

  17. - (void)viewDidLoad {  

  18.     [super viewDidLoad];  

  19.     _mWebView.delegate = self;  

  20.       

  21.     //打開URL  

  22.     NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];  

  23.     [self.mWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath: path]]];  

  24. }  

  25.   

  26. - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{  

  27.     NSString *urlstr = request.URL.absoluteString;  

  28.     NSRange range = [urlstr rangeOfString:@"ios://jwzhangjie"];  

  29.     if (range.length!=0) {  

  30.         _js_call_oc_show.text = [NSString stringWithFormat:@"請訪問地址:%@", urlstr];  

  31.     }  

  32.     return YES;  

  33. }  

  34.   

  35. -(void)webView:(nonnull UIWebView *)webView didFailLoadWithError:(nullable NSError *)error{  

  36.     NSLog(@"加載失敗");  

  37. }  

  38.   

  39. -(void)webViewDidStartLoad:(nonnull UIWebView *)webView{  

  40.     NSLog(@"開始加載");  

  41. }  

  42.   

  43.   

  44. -(void)webViewDidFinishLoad:(nonnull UIWebView *)webView{  

  45.     NSLog(@"開始結束");  

  46. //    對於調用js的時候最好這個方法裏面或者之後  

  47. }  

  48.   

  49.   

  50. - (void)didReceiveMemoryWarning {  

  51.     [super didReceiveMemoryWarning];  

  52.     // Dispose of any resources that can be recreated.  

  53. }  

  54.   

  55.   

  56.   

  57. - (IBAction)ocCallJsNoParams:(id)sender {  

  58.     NSString *js = [NSString stringWithFormat:@"ocCallJsNoParamsFunction();"];  

  59.     [self.mWebView stringByEvaluatingJavaScriptFromString:js];  

  60. }  

  61.   

  62. - (IBAction)ocCallJsHasParams:(id)sender {  

  63.     NSString *js = [NSString stringWithFormat:@"ocCallJsHasParamsFunction('%@','%@');",@"jwzhangjie",@"http://jwzhangjie.cn"];  

  64.     [self.mWebView stringByEvaluatingJavaScriptFromString:js];  

  65. }  

  66. @end  


[javascript] view plain copy

  1. function ocCallJsNoParamsFunction()  

  2. {  

  3.     alert("OC調用JS中的無參方法");  

  4.     var e = document.getElementById("js_shouw_text");  

  5.     e.options.add(new Option("OC調用JS中的無參方法", 2));  

  6. }  

  7.   

  8. function ocCallJsHasParamsFunction(name, url)  

  9. {  

  10.     alert(name+"的博客地址爲:"+url);  

  11.     var e = document.getElementById("js_shouw_text");  

  12.     e.options.add(new Option("OC調用JS中的有參方法", 2));  

  13. }  


[html] view plain copy

  1. <!DOCTYPE html>  

  2. <html lang="zh-CN">  

  3. <head>  

  4.     <meta charset="utf-8">  

  5.     <title>OC與JS互相調用</title>  

  6. </head>  

  7. <body>  

  8.     <div >  

  9.         <select id="js_shouw_text">  

  10.             <option>  

  11.                 展示OC調用JS無參數  

  12.             </option>  

  13.         </select>  

  14.     </div>  

  15.     <div>  

  16.         <BR/>  

  17.         <input type="button" value="JS調用OC方法" onclick="js_call_oc()"/>  

  18.     </div>  

  19.     <!--  這裏要清楚,雖然test.js跟index.html不同及目錄,實際安裝到程序裏面後,是在同級目錄的,所以這裏src不能加目錄,同樣css也是一樣的  -->  

  20.     <script type="text/javascript" src="test.js" charset="UTF-8"></script>  

  21.     <script type="text/javascript">  

  22.         function js_call_oc()  

  23.         {  

  24.             var iFrame;  

  25.             iFrame = document.createElement("iframe");  

  26.             iFrame.setAttribute("src", "ios://jwzhangjie");  

  27.             iFrame.setAttribute("style", "display:none;");  

  28.             iFrame.setAttribute("height", "0px");  

  29.             iFrame.setAttribute("width", "0px");  

  30.             iFrame.setAttribute("frameborder", "0");  

  31.             document.body.appendChild(iFrame);  

  32.             // 發起請求後這個iFrame就沒用了,所以把它從dom上移除掉  

  33.             iFrame.parentNode.removeChild(iFrame);  

  34.             iFrame = null;  

  35.         }  

  36.           

  37.     </script>  

  38. </body>  

  39.   

  40. </html>  


規避1:對於OC去調用JS內容最好在webViewDidFinishLoad方法裏或者之後

規避2:在html裏面引用js或者css的時候src不要帶有路徑,因爲安裝後文件都在同級目錄下面

規避3:OC調用JS的規範

[objc] view plain copy

  1. NSString *js = [NSString stringWithFormat:@"ocCallJsHasParamsFunction('%@','%@');",@"jwzhangjie",@"http://jwzhangjie.cn"];  

  2.    [self.mWebView stringByEvaluatingJavaScriptFromString:js];  

規避4:JS調用OC,這裏通過html裏面發送一個請求,然後在ios中使用shouldStartLoadWithRequest攔截請求,根據請求url的不同進行處理。


[javascript] view plain copy

  1. function js_call_oc()  

  2.        {  

  3.            var iFrame;  

  4.            iFrame = document.createElement("iframe");  

  5.            iFrame.setAttribute("src""ios://jwzhangjie");  

  6.            iFrame.setAttribute("style""display:none;");  

  7.            iFrame.setAttribute("height""0px");  

  8.            iFrame.setAttribute("width""0px");  

  9.            iFrame.setAttribute("frameborder""0");  

  10.            document.body.appendChild(iFrame);  

  11.            // 發起請求後這個iFrame就沒用了,所以把它從dom上移除掉  

  12.            iFrame.parentNode.removeChild(iFrame);  

  13.            iFrame = null;  

  14.        }  


[objc] view plain copy

  1. - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{  

  2.     NSString *urlstr = request.URL.absoluteString;  

  3.     NSRange range = [urlstr rangeOfString:@"ios://jwzhangjie"];  

  4.     if (range.length!=0) {  

  5.         _js_call_oc_show.text = [NSString stringWithFormat:@"請訪問地址:%@", urlstr];  

  6.     }  

  7.     return YES;  

  8. }  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章