iOS: 在Object-C中监听javascript事件( Javascript communicating back with Objective-C code)

iOS开发之Objective-C与JavaScript交互操作 中我们可以通过stringByEvaluatingJavaScriptFromString 去实现在obj-C中获取到相关节点属性,添加javascript代码等功能。但是我们如何监听到javascript的响应事件呢。在MAC OS中有效的API去实现,但iPhone没有,但我们有一个技巧途径:

大概思路是:在JavaScript事件响应时,通过设置document.location,这会引发webview的一个delegate方法,从而实现发送通知的效果,即达到监听的目的。

1、在javascript与webView之间定一个协议约定:

     myapp:myfunction:myparam1:myparam2

2、在javascript中添加代码:

document.location = "myapp:" + "myfunction:" + param1 + ":" + param2;

3、在webView的delegate方法webView:shouldStartLoadWithRequest:navigationType:  添加

- (BOOL)webView:(UIWebView *)webView2 
    shouldStartLoadWithRequest:(NSURLRequest *)request 
    navigationType:(UIWebViewNavigationType)navigationType {
 
    NSString *requestString = [[request URL] absoluteString];
    NSArray *components = [requestString componentsSeparatedByString:@":"];
 
    if ([components count] > 1 && 
        [(NSString *)[components objectAtIndex:0] isEqualToString:@"myapp"]) {
        if([(NSString *)[components objectAtIndex:1] isEqualToString:@"myfunction"]) 
        {
 
            NSLog([components objectAtIndex:2]); // param1
            NSLog([components objectAtIndex:3]); // param2
            // Call your method in Objective-C method using the above...
        }
        return NO;
    }
 
    return YES; // Return YES to make sure regular navigation works as expected.
}

 

 

check:http://stackoverflow.com/questions/5671742/send-a-notification-from-javascript-in-uiwebview-to-objectivec

http://www.codingventures.com/2008/12/using-uiwebview-to-render-svg-files/

 

 

 

 

 

 

posted on 2012-12-01 17:01  老Zhan  阅读(3913)  评论(0编辑  收藏  举报