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.
开发者_如何学CIs 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;
}
精彩评论