开发者

How to use Javascript to communicate with Objective-c code?

In a native iPhone app, I use a UIWebView to load a web page.

I want to use JavaScript in the web page to communicate back with the Objective-C code, for example invoke a function in Objective-C code.

开发者_如何学C

Is there any way to implement this?


There is no "direct" way to do this, but you could utilize the UIWebViewDelegate and trap a link with a custom scheme, so in your markup, you'd write something like this:

<a href="myapp://app_action?doSomething">Do Something</a>

Then, in your UIWebViewDelegate's -webView:shouldStartLoadWithRequest:navigationType: method, write something like this:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if([[[request URL] scheme] isEqualToString:@"myapp"]) { 
       SEL selector = NSSelectorFromString([[request URL] query]);
       if([self respondsToSelector:selector]) {
          [self performSelector:selector];
       } else {
          //alert user of invalid URL
       }
       return NO;
    }
    return YES;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜