I need to know what should be done to use JavaScript in a HTML sitting in UIWebView to notify Objective-C that something has happened?
To be more exact, I’m playing some JavaScript animation in HTML and I need to alert the Objective-C code that the animation has ended.
There seems to be no official method of doing this. However, the standard workaround involves reading and parsing incoming URL requests, basically rolling your own serialized messaging protocol. The message handling should be done in the
webView:shouldStartLoadWithRequest:navigationTypemethod of your view controller.Note: there are several free libraries (PhoneGap, QuickConnect, JS-to-Cocoa Bridge) which wrap this functionality (plus do a whole lot more). To reinvent the wheel (or know why it’s round, so to speak), read on.
From JavaScript, you will invoke the callback by attempting to navigate to a new URL:
In Objective-C, implement the
UIWebViewDelegateprotocol in your.hfile:Next, implement the method in your
.mfile:Two important notes:
Context: navigating to
myapp:whateverwill (of course) fail under any other context. Keep this in mind if you’re loading cross-platform pages.Timing: if a second
window.location =call is made before the first returns, it will get ‘lost.’ So, either lump your calls together, manually delay execution, or implement a queue which combines the above with JS queries into Objective-C objects.