我有一个 WebView,我想从 JavaScript 调用 Objective-C 中的视图。有人知道我该怎么做吗?
我的 ViewController 中有这段代码:
- (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]); [[Airship shared] displayStoreFront]; //<- This is the code to open the Store
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.
}
在 JavaScript 中:
function store(event)
{
document.location = "myapp:" + "myfunction:" + param1 + ":" + param2;
}
但什么也没发生。
标准解决方法为UIWebView
就是设置一个UIWebViewDelegate
,并实现该方法webView:shouldStartLoadWithRequest:navigationType: http://developer.apple.com/iphone/library/documentation/uikit/reference/UIWebViewDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/intfm/UIWebViewDelegate/webView:shouldStartLoadWithRequest:navigationType:。在您的 JavaScript 代码中,导航到某个虚假 URL,该 URL 对您要传递给应用程序的信息进行编码,例如:
window.location = "fake://myApp/something_happened:param1:param2:param3";
在您的委托方法中,查找这些假 URL,提取您需要的信息,采取任何适当的操作,然后返回NO
取消导航。如果您使用以下命令推迟任何冗长的处理,这可能是最好的一些味道performSelector http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/doc/uid/20000050-SW20.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)