Adam Waite
Adam Waite

Reputation: 18855

Listen for notifications in Objective-C from UIWebView Javascript

Is it possible to listen for a notification posted by Javascript in a UIWebView? Or similar? I have thought about repeating a function in Objective-C that monitors a JS variable but surely there is a better way?

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. I don't want to use a gif in the web view!

i.e.

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

Upvotes: 0

Views: 1087

Answers (1)

Omar Abdelhafith
Omar Abdelhafith

Reputation: 21221

The only way to pass event from your html page to the iPhone app, is by using url,

When you want to pass a special even, make your js change ur navigation to a new url, say for example, "MyCustomURl://DoSomeThing"

Now in your iPhone application, set the delegate of the webView to be 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;
}

Upvotes: 2

Related Questions