24

How would I expose an Objective-C method within JavaScript when using the iPhone SDK when using the UIWebView?

Any help would be appreciated!

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
Luke
  • 6,195
  • 11
  • 57
  • 85

3 Answers3

22

The best way to do this would be through a custom link, and then use the UIWebView delegate method -webView:shouldStartLoadWithRequest:navigationType: to trap requests. When you see a request come through with your link in it, you know your action has been triggered.

Ben Gottlieb
  • 85,404
  • 22
  • 176
  • 172
  • 1
    I do not believe this will work, when I was testing something similar the resource policy delegates were only called in response to user initiated actions, script initiates actions were silently dropped. it is possible this has changed since I checked back in June. – Louis Gerbarg Oct 29 '08 at 05:44
  • 1
    I just tried a very simple page who's onload function set the page's location to www.google.com, and the request was passed to the delegate. – Ben Gottlieb Oct 29 '08 at 21:04
  • Just used this method in my app. Thanks! – James Skidmore Mar 02 '10 at 04:23
3

There is an example application in the QuickConnectiPhone framework that shows you how to do this.

QuickConnectiPhone also gives you a JavaScript function called 'makeCall'. You pass it a command and an array of parameters and it will pass them to the Objective-C side of your app for handling. You can then make your function call.

You can find it here on Sourceforge.

jamesh
  • 19,863
  • 14
  • 56
  • 96
Lee
  • 751
  • 5
  • 2
0

To see an example of this check out the PhoneGap source code from Github:

http://github.com/sintaxi/phonegap/tree/master/iphone/Classes/GlassAppDelegate.m

keremk
  • 2,303
  • 14
  • 10