JavaScript和OC交互

--------------------------JS中调用OC的方法---------------------------

导入这个包  javascriptCore.framework

添加头文件
#import

OC代码
// 设备的宽高(宏定义)
#define HScreen [[UIScreen mainScreen] bounds].size.height
#define WScreen [[UIScreen mainScreen] bounds].size.width

//初始化webView
_webView . frame = CGRectMake ( 0 , 0 , WScreen , ViewHeight ( self . view ));
_webView . delegate = self ;

//获取html地址并用webView加载地址(本地就设置本地的,网络的就设置网络加载)
//网络加载html
[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[[NSString stringWithFormat:@"%@?system=iOS&version=%@",self.hfModel.playUrl,LOCAL_VER_STR] stringByReplacingOccurrencesOfString:@" " withString:@""]]]];

//本地加载html
NSString *htmlPath=[[ NSBundle mainBundle ] resourcePath ];
htmlPath=[htmlPath stringByAppendingPathComponent:@"/test.html"];
NSURL *localURL=[[ NSURL alloc ] initFileURLWithPath :htmlPath];
[ _webView loadRequest :[ NSURLRequest requestWithURL :localURL]];

//获取JS请求类型
JSContext *context = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

//JS需要调用的方法 (textJStoOCbody 此方法就是JS需要调用的方法<这是客户端和服务端商定好的函数名称>
 context[ @"textJStoOCbody" ] = ^() {//这使用block的方式来实现的
        NSArray *argsContent = [JSContext currentArguments];//获取JS给OC传的值
          
      //<处理数据方法1.得到指定的某个数据>判断是否有数据(有数据的处理)
        if (argsContent. count ) {
           
id dataValue = [[ NSString stringWithFormat : @"%@" ,argsContent[ 0 ]] JSONObject ];
           
NSLog ( @"%@" ,dataValue);
        }

        NSArray *args = [JSContext currentArguments]; //获取JS给OC传的值
        NSDictionary *dic;
        // <处理数据方法2>返回的json数据解析处理
        for ( JSValue *jsVal in args) {
            dic = [jsVal
toDictionary ];
           
NSLog ( @"%@" ,dic);
           
NSString *str = [ NSString stringWithFormat : @"%@" ,jsVal];
           
id dataValue = [str JSONObject ];
           
NSLog ( @"%@" , dataValue);
        }
       
       
JSValue *this = [ JSContext currentThis ];
       
NSLog ( @"%@" ,this. context . description );
        NSLog(@"-------End Log-------");
        return dic;//这很重要。这是给JS调用此方法后的返回值<自己控制返回什么>
    };

//抓取JS异常
context.exceptionHandler = ^(JSContext *con, JSValue *exception) { 
NSLog(@"%@", exception); 
con.exception = exception; 
}; 

javascript代码  
"-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html40/strict.dtd" >


name = "viewport" content = "width=device-width, target-densitydpi=device-dpi" />
http-equiv = "Content-Type" content = "text/html; charset=UTF-8" >



测试 js 使用

id = 'btntest' onclick = 'buttonClick()' > 调用 iOS 方法

--------------------OC调用JS中的方法------------------
//调用JS的方法最好在webView加载完成以后调用
- (void)webViewDidFinishLoad:(UIWebView *)webView {
     [_webView stringByEvaluatingJavaScriptFromString:@"stealth()"];
}

你可能感兴趣的:(iOS,JavaScript)