OCとJSの呼び出し

6325 ワード

最近のプロジェクトではhtml 5を用いて実装されるが,OC呼び出しJS,およびJS呼び出しOCの方法については,ここで問題点と実装方法を紹介する.
//
//  ViewController.h
//  OC_And_JS
//
//  Created by    on 15/7/9.
//  Copyright © 2015    . All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UIWebViewDelegate>

@property (weak, nonatomic) IBOutlet UIButton *oc_call_js_no_params;
@property (weak, nonatomic) IBOutlet UIButton *oc_call_js_has_params;
@property (weak, nonatomic) IBOutlet UIWebView *mWebView;
@property (weak, nonatomic) IBOutlet UILabel *js_call_oc_show;

- (IBAction)ocCallJsNoParams:(id)sender;
- (IBAction)ocCallJsHasParams:(id)sender;


@end
//
//  ViewController.m
//  OC_And_JS
//
//  Created by    on 15/7/9.
//  Copyright © 2015    . All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _mWebView.delegate = self;
    
    //  URL
    NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    [self.mWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath: path]]];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSString *urlstr = request.URL.absoluteString;
    NSRange range = [urlstr rangeOfString:@"ios://jwzhangjie"];
    if (range.length!=0) {
        _js_call_oc_show.text = [NSString stringWithFormat:@"     :%@", urlstr];
    }
    return YES;
}

-(void)webView:(nonnull UIWebView *)webView didFailLoadWithError:(nullable NSError *)error{
    NSLog(@"    ");
}

-(void)webViewDidStartLoad:(nonnull UIWebView *)webView{
    NSLog(@"    ");
}


-(void)webViewDidFinishLoad:(nonnull UIWebView *)webView{
    NSLog(@"    ");
//        js               
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (IBAction)ocCallJsNoParams:(id)sender {
    NSString *js = [NSString stringWithFormat:@"ocCallJsNoParamsFunction();"];
    [self.mWebView stringByEvaluatingJavaScriptFromString:js];
}

- (IBAction)ocCallJsHasParams:(id)sender {
    NSString *js = [NSString stringWithFormat:@"ocCallJsHasParamsFunction('%@','%@');",@"jwzhangjie",@"http://jwzhangjie.cn"];
    [self.mWebView stringByEvaluatingJavaScriptFromString:js];
}
@end
function ocCallJsNoParamsFunction()
{
    alert("OC  JS      ");
    var e = document.getElementById("js_shouw_text");
    e.options.add(new Option("OC  JS      ", 2));
}

function ocCallJsHasParamsFunction(name, url)
{
    alert(name+"      :"+url);
    var e = document.getElementById("js_shouw_text");
    e.options.add(new Option("OC  JS      ", 2));
}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <title>OC JS    </title>
</head>
<body>
    <div >
        <select id="js_shouw_text">
            <option>
                  OC  JS   
            </option>
        </select>
    </div>
    <div>
        <BR/>
        <input type="button" value="JS  OC  " onclick="js_call_oc()"/>
    </div>
    <!--       ,  test.js index.html     ,          ,       ,    src     ,  css       -->
    <script type="text/javascript" src="test.js" charset="UTF-8"></script>
    <script type="text/javascript">
        function js_call_oc()
        {
            var iFrame;
            iFrame = document.createElement("iframe");
            iFrame.setAttribute("src", "ios://jwzhangjie");
            iFrame.setAttribute("style", "display:none;");
            iFrame.setAttribute("height", "0px");
            iFrame.setAttribute("width", "0px");
            iFrame.setAttribute("frameborder", "0");
            document.body.appendChild(iFrame);
            //        iFrame    ,     dom    
            iFrame.parentNode.removeChild(iFrame);
            iFrame = null;
        }
        
    </script>
</body>

</html>

回避1:OCに対してJSの内容を呼び出すのは最も良いです
WebViewDidFinishLoadメソッドまたはその後
回避2:htmlでjsまたはcssを参照するときにsrcにパスを持たないでください.インストール後のファイルはすべて同級ディレクトリの下にあるからです.
回避3:OC呼び出しJSの仕様
 NSString *js = [NSString stringWithFormat:@"ocCallJsHasParamsFunction('%@','%@');",@"jwzhangjie",@"http://jwzhangjie.cn"];
    [self.mWebView stringByEvaluatingJavaScriptFromString:js];
回避4:JS呼び出しOC,ここでhtmlでリクエストを送信しiosで使用
shouldStartLoadWithRequestブロックリクエストは、リクエストurlによって処理されます.
 function js_call_oc()
        {
            var iFrame;
            iFrame = document.createElement("iframe");
            iFrame.setAttribute("src", "ios://jwzhangjie");
            iFrame.setAttribute("style", "display:none;");
            iFrame.setAttribute("height", "0px");
            iFrame.setAttribute("width", "0px");
            iFrame.setAttribute("frameborder", "0");
            document.body.appendChild(iFrame);
            //        iFrame    ,     dom    
            iFrame.parentNode.removeChild(iFrame);
            iFrame = null;
        }
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSString *urlstr = request.URL.absoluteString;
    NSRange range = [urlstr rangeOfString:@"ios://jwzhangjie"];
    if (range.length!=0) {
        _js_call_oc_show.text = [NSString stringWithFormat:@"     :%@", urlstr];
    }
    return YES;
}

ソースアドレス:
http://jwzhangjie.cn/forum.php?mod=viewthread&tid=3&page=1&extra=#pid3