Obl*_*iux 41 iphone cocoa-touch uiwebview
我有一个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.
}
Run Code Online (Sandbox Code Playgroud)
并在Javascript中:
function store(event)
{
document.location = "myapp:" + "myfunction:" + param1 + ":" + param2;
}
Run Code Online (Sandbox Code Playgroud)
但没有任何反应.
Six*_*tto 52
标准的解决方法UIWebView是设置a UIWebViewDelegate并实现该方法webView:shouldStartLoadWithRequest:navigationType:.在您的JavaScript代码中,导航到一些伪造的URL,该URL会对您要传递给应用的信息进行编码,例如:
window.location = "fake://myApp/something_happened:param1:param2:param3";
Run Code Online (Sandbox Code Playgroud)
在您的委托方法中,查找这些虚假URL,提取您需要的信息,采取适当的操作,然后返回NO取消导航.如果你推迟使用某种味道的performSelector任何冗长的处理,这可能是最好的.
tal*_*kol 32
不建议从JS调用目标c的window.location方法.问题的一个例子:如果你进行两次立即连续调用,则忽略一次(因为你不能太快地改变位置) - 自己尝试一下..
我推荐以下替代方法:
function execute(url)
{
var iframe = document.createElement("IFRAME");
iframe.setAttribute("src", url);
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
iframe = null;
}
Run Code Online (Sandbox Code Playgroud)
您execute重复调用该函数,并且由于每个调用都在其自己的iframe中执行,因此在快速调用时不应忽略它们.
这个家伙的功劳.
| 归档时间: |
|
| 查看次数: |
48065 次 |
| 最近记录: |