首页 > 代码库 > 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相互调用