UIViewWeb与JS交互(已经放弃)

随着程序的开发,发现IOS中使用OC和js的交互越越多,这里就先做以下对简单的OC与JS交互,进行总结。总体效果如下:

oc_js_07.gif

这里对对ios中OC与JS简单的交互进行介绍,以及实现。程序中简单的实现了js与OC部分的信息的交互。

1、从OC控制js中的代码调用的是stringByEvaluatingJavaScriptFromString实现具体代码如下

#pragma mark 调用js中的方法实现OC同步到js

- (IBAction)synchronizationJS:(id)sender {

NSString* js = [NSString stringWithFormat:@"oc_synchronization_to_js('%@','%@')",self.useNameText.text,self.userPassWord.text];

[self.webView stringByEvaluatingJavaScriptFromString:js];

}

#pragma mark 调用js的方法实现OC清空js

- (IBAction)clearJs:(id)sender {

NSString *js = [NSString stringWithFormat:@"clear_js();"];

[self.webView stringByEvaluatingJavaScriptFromString:js];

}

2、通过QWebView的代理中的方法-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;来实现js对oc的控制
具体代码如下:

#pragma mark 用于js调用清空OC的接口
-(void) clearOC
{
    self.userPassWord.text = @"";
    self.useNameText.text = @"";
}
#pragma mark 用于设置js同步到OC的接口
-(void) setName:(NSString*) name withPassWord:(NSString*) password
{
    self.useNameText.text = name;
    self.userPassWord.text = password;
}
#pragma mark  webview的代理  这里只需要处理start

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString* urlStr = request.URL.absoluteString;
    //对数据的进行处理
    //[urlStr ]
    //[urlStr rangeOfString:@"ios://clearOC"];
    if([urlStr hasPrefix:@"youling0809://clearOC"])
    {
        [self clearOC];
        return NO;
    }
    else if([urlStr hasPrefix:@"youling0809://js_synchronization_to_oc"])
    {
        NSString* urlstrTemp = [[NSMutableString alloc] initWithFormat:urlStr,nil];
       urlstrTemp =  [urlstrTemp stringByReplacingOccurrencesOfString:@"youling0809://js_synchronization_to_oc" withString:@""];
        NSArray* array = [urlstrTemp componentsSeparatedByString:@"__________"];
        [self setName:array[0] withPassWord:array[1]];
        return NO;
    }
    return YES;
}

3、当然只有这些是不够的还需要js界面的配合以下,js的代码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>幽灵OC和js的交互</title>
    </head>
    <body>
        <center>
            <span>js部分</span>
        </center>
        <center>
            <span>用户名:</span>
            <input type="text" id="userName" name="userName" width="150px"/>
        </center>
        <center>
            <span>密    码:</span>
            <input type="text" id="passWord" name="passWord" width="150px" />
        </center>
        <center>
            <span>                </span>
            <input type="button" id="synchronization_to_oc" value="js数据同步到OC" width="60px" height="24px" onclick="js_synchronization_to_oc()"/>
        </center>
            <center>
            <span>                </span>
            <input type="button" name="clearOC" id="clearOC" value="清空OC数据" width="60px" height="24px" onclick="js_clear_oc()"/>
        </center>
        <script type="text/javascript">
        /*
         * 清空oc数据
         */
        function js_clear_oc(){
            //alert(1234);
            var iFrame;
            iFrame = document.createElement("iframe");
            iFrame.setAttribute("src", "youling0809://clearOC");
            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;
        }
        /*
         * 清空JS数据
         */
        function clear_js(){
            document.getElementById('userName').value = "";
            document.getElementById('passWord').value = "";
        }
        /*
         * 同步js到OC
         */
        function js_synchronization_to_oc(){
            //alert(1234);
            var iFrame;
            iFrame = document.createElement("iframe");
            iFrame.setAttribute("src", "youling0809://js_synchronization_to_oc"+document.getElementById('userName').value+"__________"+document.getElementById('passWord').value);
            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;
        }
        /*
         * 同步OC到JS
         */
        function oc_synchronization_to_js(name,password01){
            document.getElementById('userName').value = name;
            document.getElementById('passWord').value = password01;
            //alert(123);
            }
        </script>
    </body>
</html>

上面讲到的UIWebView与js的交互主要是通过拦截js中开始加载的url进行处理来完成js对OC中方法的调用,下面我们说下如何在js中直接调用IOS中的方法。在IOS7.0之后IOS的API中有了JavaScriptCore可以用来完成IOS与web的交互。
首先需要导入头文件:

#import <JavaScriptCore/JavaScriptCore.h>

点开JavaSC
这里在OC中主要要到了两个类:JSContext和JSValue,在-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType,中添加方法js_synchronization并且在block中实现就行了,如果能够确定所穿的参数的个数可以直接给block添加参数用来接收值,如果不确定的话,block可以不传值,可以通过JSContext.currentArguments来获取。

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    JSContext* context =  [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    /*
     *在这里的js_synchronization 是在js中想要调用方法
     */
    /*确定传输参数的个数时,就直接在block中添加就可以了*/
    context[@"js_synchronization"] = ^(JSValue* value1,JSValue* value2){
        NSLog(@"我传递的参数value1 = %@",value1.toString);
        NSLog(@"我传递的参数value2 = %@",value2.toString);
        dispatch_async(dispatch_get_main_queue(), ^{
            self.useNameText.text = value1.toString;
            self.userPassWord.text = value2.toString;
        });
        
        
    };
    //如果不知道参数的个数
    /*context[@"js_synchronization"] = ^(){
        NSArray* array =  JSContext.currentArguments;
        for (int i  =0; i < array.count; i++) {
            JSValue* value = array[i];
            NSLog(@"%@",value.toString);
        }
    };*/
    return  true;
    
}

在JS中直接调用js_synchronization(bbb,aaa);就可以了,具体的代码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>幽灵OC和js的交互</title>
    </head>
    <body>
        <center>
            <span>js部分</span>
        </center>
        <center>
            <span>用户名:</span>
            <input type="text" id="userName" name="userName" width="150px"/>
        </center>
        <center>
            <span>密码:</span>
            <input type="text" id="passWord" name="passWord" width="150px" />
        </center>
        <center>

            <input type="button" id="synchronization_to_oc" value="js数据同步到OC" width="60px" height="24px" onclick="js_synchronization_to_oc()"/>
        </center>
            <center>
            <span>                </span>
            <input type="button" name="clearOC" id="clearOC" value="清空OC数据" width="60px" height="24px" onclick="js_clear_oc()"/>
        </center>
        <script type="text/javascript">
        /*
         * 清空oc数据
         */
        function js_clear_oc(){
            js_synchronization("","");
        }
        /*
         * 清空JS数据
         */
        function clear_js(){
            document.getElementById('userName').value = "";
            document.getElementById('passWord').value = "";
        }
        /*
         * 同步js到OC
         */
        function js_synchronization_to_oc(){
            
           var aaa =  document.getElementById('passWord').value;
           var bbb = document.getElementById('userName').value;
           
            js_synchronization(bbb,aaa);
        }
        /*
         * 同步OC到JS
         */
        function oc_synchronization_to_js(name,password01){
            document.getElementById('userName').value = name;
            document.getElementById('passWord').value = password01;
            //alert(123);
            }
        </script>
    </body>
</html>

Demo的下载地址为:https://github.com/IOSYUNYUN/oc_js_01.git

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容