gpt4 book ai didi

ios - 如何将事件从在 UIWebView 中运行的 HTML 发送到 native Objective-C 代码?

转载 作者:技术小花猫 更新时间:2023-10-29 11:12:37 24 4
gpt4 key购买 nike

我想在 iOS 应用程序中集成一个完整的 HTML 框架(即 HTML/CSS/JavaScript),并使负责运行 HTML 内容的 UIWebView 能够与 native Objective-C 源代码的其余部分进行通信。

方向 1:从 Objective-C 到 UIWebView 中的 HTML

让源代码的其余部分向 HTML 内容发送消息的方法非常简单:我只需在 Objective-C 端调用 stringByEvaluatingJavaScriptFromString: 并以正确的方式实现 JavaScript 方法。

方向 2:从 UIWebView 中的 HTML 到 Objective-C

这是我无法真正弄清楚的方式。到目前为止,我唯一的想法是让我的应用程序成为本地网络服务器,并向其发送 HTML 请求。但我不知道如何做到这一点,尽管我认为它可能是骨子里的东西,因为我相信诸如 Things、VLC 或 1Password 之类的应用程序可能会使用这种功能。

欢迎任何使此方向 2 工作的想法或任何使 HTML 内容中的事件发送到 Objective-C 代码的新观点。

最佳答案

我已经使用 jQuery 和 UIWebViewDelegate 完成了这个:

JavaScript(jQuery 移动版):

$("#bloodType").change(function() {
url = $("#bloodType option:selected").text();
url = "donordialog:bloodTypeChanged(" + url + ")";
window.location = url;
});

因此,生成的 URL 如下所示:donordialog:bloodTypeChanged(typeAB-)

在我的目标代码中:

-(BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL *URL = [request URL];
if ([[URL scheme] isEqualToString:@"donordialog"])
{
// now we need to figure out the function part
NSString *functionString = [URL resourceSpecifier];

if ([functionString hasPrefix:@"bloodTypeChanged"])
{
// the blood type has changed, now do something about it.
NSString *parameter = [functionString stringByReplacingOccurrencesOfString:@"bloodTypeChanged" withString:@""];

// remove the '(' and then the ')'
parameter = [parameter stringByReplacingOccurrencesOfString:@"(" withString:@""];
parameter = [parameter stringByReplacingOccurrencesOfString:@")" withString:@""];

// log the paramter, as I don't know what to do with it right now
NSLog(@"%@", parameter);
}

return NO;
}

return YES;
}

这段代码是从我目前正在进行的项目中逐字复制的,可以验证它是否有效。

关于ios - 如何将事件从在 UIWebView 中运行的 HTML 发送到 native Objective-C 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9888142/

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