首页 > 代码库 > IOS Object和javaScript相互调用

IOS Object和javaScript相互调用

在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=http://www.mamicode.com/=‘‘){var video = document.getElementsByTagName(‘source‘)[0];}document.location = ‘myvideo‘+ video.getAttribute(‘src‘);injectedObject.playVideo(video.getAttribute(‘src‘));}}";>

说明如下:

(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相互调用