zoukankan      html  css  js  c++  java
  • iOS js oc相互调用JavaScriptCore(一)

    原址:http://blog.csdn.net/lwjok2007/article/details/47058101

    1、普通调用

    从iOS7开始 苹果公布了JavaScriptCore.framework 它使得JS与OC的交互更加方便了。

    下面我们就简单了解一下这个框架

    首先我导入framework

    方法如下

    点击Linked Frameworks and Libraries 的添加后 选择 JavaScriptCore.framework

    选中JavaScriptCore.framework后 点击右下角Add 添加完成

    好 创建完成之后我们导入一下头文件

    [objc] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #import <JavaScriptCore/JavaScriptCore.h>  


    点进去 会看到如下几个方法

    #import "JSContext.h"

    #import "JSValue.h"

    #import "JSManagedValue.h"

    #import "JSVirtualMachine.h"

    #import "JSExport.h"

    这些方法我们等会再细讲

    下来我们创建一个UIWebView  用来测试

    创建UIWebView

    [objc] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. UIWebView *myWebView;  


    初始化,添加,打开网址

    [objc] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. //初始化webview  
    2. myWebView=[[UIWebView alloc]initWithFrame:CGRectMake(0, 22, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-22)];  
    3. myWebView.delegate=self;  
    4. //添加webview到当前viewcontroller的view上  
    5. [self.view addSubview:myWebView];  
    6.   
    7. //网址  
    8. NSString *httpStr=@"https://www.baidu.com";  
    9. NSURL *httpUrl=[NSURL URLWithString:httpStr];  
    10. NSURLRequest *httpRequest=[NSURLRequest requestWithURL:httpUrl];  
    11. [myWebView loadRequest:httpRequest];  



    运行效果如下

    下面我们来实现UIWebView的几个代理方法

    首先我们看下它的代理方法

    [objc] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. @protocol UIWebViewDelegate <NSObject>  
    2.   
    3. @optional  
    4. - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;  
    5. - (void)webViewDidStartLoad:(UIWebView *)webView;  
    6. - (void)webViewDidFinishLoad:(UIWebView *)webView;  
    7. - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;  
    8.   
    9. @end  


    每个方法的作用等会在带里面做注释

    首先我们添加协议

    [objc] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. @interface ViewController ()<UIWebViewDelegate>  


    实现代理方法

    [objc] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. #pragma mark --webViewDelegate  
    2. -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType  
    3. {  
    4.     //网页加载之前会调用此方法  
    5.       
    6.     //retrun YES 表示正常加载网页 返回NO 将停止网页加载  
    7.     return YES;  
    8. }  
    9.   
    10. -(void)webViewDidStartLoad:(UIWebView *)webView  
    11. {  
    12.     //开始加载网页调用此方法  
    13. }  
    14.   
    15. -(void)webViewDidFinishLoad:(UIWebView *)webView  
    16. {  
    17.     //网页加载完成调用此方法  
    18. }  
    19.   
    20. -(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error  
    21. {  
    22.     //网页加载失败 调用此方法  
    23. }  



    每个方法是什么时候调用都在注释里面

    下来我们先尝试用oc调用一下js方法

    [objc] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. -(void)webViewDidFinishLoad:(UIWebView *)webView  
    2. {  
    3.     //网页加载完成调用此方法  
    4.       
    5.     //首先创建JSContext 对象(此处通过当前webView的键获取到jscontext)  
    6.     JSContext *context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];  
    7.     NSString *alertJS=@"alert('test js OC')"; //准备执行的js代码  
    8.     [context evaluateScript:alertJS];//通过oc方法调用js的alert  
    9.       
    10. }  


    执行效果如下:

    好了,我们已经实现了iOS 调用js

    2、带参数调用

    1、需要在网页load完毕之后才能调用

    [objc] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. - (void)webViewDidFinishLoad:(UIWebView *)webView {  
    2.     [self signInWithJs:5];  
    3. }  

    2、执行js语句

    [objc] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. - (void)signInWithJs:(NSInteger)signDay {  
    2.     NSString* js = [NSString stringWithFormat:@"signIn('%d','%@');", signDay, @"test"];  
    3.     NSString* strTemp = [jsWebView stringByEvaluatingJavaScriptFromString:js];  
    4. }  
    [objc] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. </pre><pre code_snippet_id="1692469" snippet_file_name="blog_20141229_2_9714948" class="objc" name="code">  

    原址:http://www.2cto.com/kf/201402/281505.html

    本例子是为了让大家能快速开发出OC调用JS功能的一个简单的例子。

    1、准备一个本地化的html网页,如jsIOS.html

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    <meta http-equiv="content-type"content="text/html;charset=utf-8">
        <title>js调用oc</title>
        <script type="text/javaScript">
            function postStr(str1,str2){
                document.getElementById("text1").value=str1;
                document.getElementById("text2").value=str2;
                returndocument.getElementById("text3").value;
                //return "javaScript返回值啦";
            }
         
        </script>
         
     
    <p><input type="text"id="text1"value="实参1"></p>
    <p><input type="text"id="text2"value="实参2"></p>
    <p><input type="text"id="text3"value="返回值"></p>



    2、将此html文件放到项目代码目录里面,如图:

    3、拖一个UIWebView控件和UIButton控件到xxxViewController对应的.xib或.storyboard视图的UIView上;

    在xxxViewController的.h文件中分别声明UIWebView类型变量和UIButton类型的变量,以及一个按钮点击事件(并且跟视图里面的控件连线),

    并且添加一个UIWebViewDelegate类型的委托。<喎�"http://www.2cto.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+eHh4Vmlld0NvbnRyb2xsZXIuaM7EvP7E2sjdyOfPwqO6PC9wPgo8cD48L3A+CjxwIGNsYXNzPQ=="p1">

    1
    2
    3
    4
    5
    6
    7
    #import<uikit uikit.h="">
     
    @interfaceViewController : UIViewController <uiwebviewdelegate>
    @property(nonatomic,retain) IBOutlet UIWebView *webview;
    @property(nonatomic,retain) IBOutlet UIButton *button;
    -(IBAction)IOS_JS:(id)sender;
    @end</uiwebviewdelegate></uikit>

     

    4、在xxxViewController.m文件中实现通过点击事件,调用javaScript的方法传递多个参数并取得返回值。

    代码如下:

     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    //
    //  ViewController.m
    //  IOS_JS_01
    //
    //  Created by IMAC on 14-2-25.
    //  Copyright (c) 2014年 Wanggsx. All rights reserved.
    //
     
    #import"ViewController.h"
     
    @interfaceViewController ()
     
    @end
     
    @implementationViewController
    @synthesizewebview;
     
    - (void)viewDidLoad
    {
        [superviewDidLoad];
        //设置webView
        webview.backgroundColor = [UIColor clearColor];
        //webview.scalesPageToFit =YES;
        webview.delegate =self;
        //找到jsIOS.html文件的路径
        NSString *basePath = [[NSBundle mainBundle]bundlePath];
        NSString *helpHtmlPath = [basePath stringByAppendingPathComponent:@"jsIOS.html"];
        NSURL *url = [NSURL fileURLWithPath:helpHtmlPath];
        //加载本地html文件
        [webview loadRequest:[NSURLRequest requestWithURL:url]];
    }
     
    /*
     * 点击事件
     * 调用javaScript的方法postStr(str1,str2)并取得返回值
     * 输出返回值到控制台
     */
    -(IBAction)IOS_JS:(id)sender
    {
        //NSString *str = [self.webview stringByEvaluatingJavaScriptFromString:@"postStr();"];
        //要传递的参数一
        NSString *str1 = @"我来自于oc";
        //要传递的参数二
        NSString *str2 = @"我来自于地球";
        NSString *str = [self.webview stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"postStr('%@','%@');",str1,str2]];
        NSLog(@"JS返回值:%@",str);
    }
     
     
    - (void)didReceiveMemoryWarning
    {
        [superdidReceiveMemoryWarning];
    }
    @end
  • 相关阅读:
    fzuoj Problem 2177 ytaaa
    zoj The 12th Zhejiang Provincial Collegiate Programming Contest Capture the Flag
    zoj The 12th Zhejiang Provincial Collegiate Programming Contest Team Formation
    zoj The 12th Zhejiang Provincial Collegiate Programming Contest Beauty of Array
    zoj The 12th Zhejiang Provincial Collegiate Programming Contest Lunch Time
    zoj The 12th Zhejiang Provincial Collegiate Programming Contest Convert QWERTY to Dvorak
    zoj The 12th Zhejiang Provincial Collegiate Programming Contest May Day Holiday
    zoj The 12th Zhejiang Provincial Collegiate Programming Contest Demacia of the Ancients
    zjuoj The 12th Zhejiang Provincial Collegiate Programming Contest Ace of Aces
    csuoj 1335: 高桥和低桥
  • 原文地址:https://www.cnblogs.com/xujiahui/p/6011977.html
Copyright © 2011-2022 走看看