码迷,mamicode.com
首页 > 移动开发 > 详细

IOS Object和javaScript相互调用

时间:2014-04-29 13:26:21      阅读:319      评论:0      收藏:0      [点我收藏+]

标签:javascript   ios   object-c   

在IOS开发中有时会用到Object和javaScript相互调用,具体步骤如下:

1. Object中执行javascript代码,这个比较简单,苹果提供了很好的方法

- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script

2. javascript执行过程中返回给Object的数据或者调用Object方法,这个时候就需要用到

UIWebView的地址重定向功能,主要代码如下:

(1)创建UIWebView

    webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    webView.delegate = self;
    [self.view addSubview:webView];
    [self loadWebPageWithString:_url];

- (void)loadWebPageWithString:(NSString*)urlString
{
    NSURL *url =[NSURL URLWithString:urlString];
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
}


(2)实现UIWebView方法

#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *urlString = [[request URL] absoluteString];
    debuglog(@"urlString = %@",urlString);
    NSString *prefix = @"myvideo";
    if ([urlString hasPrefix:prefix]) {
        NSString *endString = [urlString substringFromIndex:7];
        debuglog(@"last urlString = %@",endString);
        
        return NO;
    }

    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [self excuteJavaScript];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    
}

- (void)excuteJavaScript
{
    NSString *js = @"var video =  document.getElementsByTagName(‘video‘)[0];setTimeout(getVideo,1000); function getVideo(){ video =  document.getElementsByTagName(‘video‘)[0];if(video==undefined){setTimeout(getVideo,1000);}else{ video.pause();if(video.src==‘‘){var video = document.getElementsByTagName(‘source‘)[0];}document.location = ‘myvideo‘+ video.getAttribute(‘src‘);injectedObject.playVideo(video.getAttribute(‘src‘));}}";

    [webView stringByEvaluatingJavaScriptFromString:js];
}

说明如下:

(1)在UIWebView加载完网页的时候,即执行到webViewDidFinishLoad代理的时候,执行一段javascript代码,这段代码的作用是获取网页中的视频地址,代码中“ document.location = ‘myvideo‘+ video.getAttribute(‘src‘); ”这段特别重要,document.location是为了做地址重定向用的,执行完这段javascript代码,接着就会执行

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType 这个代理方法,其中就会捕获到document.location给出的地址即‘myvideo‘+ video.getAttribute(‘src‘); 。你可以去掉‘myvideo‘头,就可以得到你需要的东西了,其中‘myvideo‘是你自己定义的一个头,是为了便于解析后面的数据。







IOS Object和javaScript相互调用

标签:javascript   ios   object-c   

原文地址:http://blog.csdn.net/chchong1234/article/details/24656257

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!