简体   繁体   English

从UIWebView Javascript中侦听Objective-C中的通知

[英]Listen for notifications in Objective-C from UIWebView Javascript

Is it possible to listen for a notification posted by Javascript in a UIWebView? 是否可以在UIWebView中侦听Javascript发布的通知? Or similar? 还是类似的? I have thought about repeating a function in Objective-C that monitors a JS variable but surely there is a better way? 我曾想过在Objective-C中重复一个监视JS变量的函数,但肯定有更好的方法吗?

I want to listen for when a particular image loads in the UIWebView (which I can do with .load method in jQuery), when the image does load I would like to hide a native UIActivityIndicator. 我想在UIWebView(我可以用jQuery中的.load方法)加载特定图像时监听,当图像加载时我想隐藏原生UIActivityIndi​​cator。 I don't want to use a gif in the web view! 我不想在网页视图中使用gif!

ie

$('img.someImage').load(function(){
//fire something for obj-c to listen to!
});

The only way to pass event from your html page to the iPhone app, is by using url, 将事件从您的html页面传递到iPhone应用程序的唯一方法是使用url,

When you want to pass a special even, make your js change ur navigation to a new url, say for example, "MyCustomURl://DoSomeThing" 当你想传递一个特殊的偶数时,让你的js改变你的导航到一个新的网址,例如, "MyCustomURl://DoSomeThing"

Now in your iPhone application, set the delegate of the webView to be self 现在,在您的iPhone应用程序中,将webView的委托设置为self

And add the following function 并添加以下功能

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *absolute = [request.URL absoluteString];

    if ([absolute isEqualToString:@"MyCustomURl://DoSomeThing"]) {
        //Do what you want here
        return NO;//this will not load the url
    }

    return YES;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM