gpt4 book ai didi

iphone - 如何从 Javascript 调用 Objective-C?

转载 作者:行者123 更新时间:2023-12-03 18:12:48 28 4
gpt4 key购买 nike

我有一个 WebView,我想从 JavaScript 调用 Objective-C 中的 View 。有人知道我该怎么做吗?

<小时/>

我的 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: 。在您的 JavaScript 代码中,导航到某个虚假 URL,该 URL 对您要传递给应用程序的信息进行编码,例如:

window.location = "fake://myApp/something_happened:param1:param2:param3";

在您的委托(delegate)方法中,查找这些虚假 URL,提取所需的信息,采取任何适当的操作,然后返回 NO 以取消导航。最好使用 some flavor of performSelector 推迟任何冗长的处理。 .

关于iphone - 如何从 Javascript 调用 Objective-C?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1662473/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com