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==''){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’是你自己定義的一個頭,是為瞭便於解析後面的數據。

發佈留言