How do I call an objective-c method?

How do I call an Objective-C method from Javascript in UIWebView?

  • I'm developing a native iPhone app using Phonegap, so everything is done in HTML and JS. I am using the Flurry SDK for analytics and want to use the [FlurryAPI logEvent:@"EVENT_NAME"]; method to track events. Is there a way to do this in Javascript? So when tracking a link I would imagine using something like <a onClick="flurryTrackEvent("Click_Rainbows")" href="#Rainbows">Rainbows</a> <a onClick="flurryTrackEvent("Click_Unicorns")" href="#Unicorns">Unicorns</a> "FlurryAPI.h" has the following: @interface FlurryAPI : NSObject { } + (void)startSession:(NSString *)apiKey; + (void)logEvent:(NSString *)eventName; + (void)logEvent:(NSString *)eventName withParameters:(NSDictionary *)parameters; + (void)logError:(NSString *)errorID message:(NSString *)message exception:(NSException *)exception; + (void)setUserID:(NSString *)userID; + (void)setEventLoggingEnabled:(BOOL)value; + (void)setServerURL:(NSString *)url; + (void)setSessionReportsOnCloseEnabled:(BOOL)sendSessionReportsOnClose; @end I'm only interested in the logEvent method(s). If it's not clear by now, I'm comfortable with JS but a recovering Obj-C noob. I've read the http://developer.apple.com/mac/library/documentation/AppleApplications/Conceptual/SafariJSProgTopics/Tasks/ObjCFromJavaScript.html#//apple_ref/doc/uid/30001215 but the examples described there are all for newly declared methods and I imagine this could be simpler to implement because the Obj-C method(s) are already defined. Thank you in advance for any input.

  • Answer:

    One way to do this is to setup a delegate on the UIWebView which has the shouldStartLoadEvent. Inside that event, you check what URL the UIWebView is trying to navigate to. Now to communicate from JavaScript to Objective-C, you need to specify your own custom anchors which will trigger different actions. For example, to log something, you might decide to use the anchor "#FAPI_LogEvent_Click_Rainbows". In JavaScript, you could have methods defined like such: function flurryTrackEvent(text) { window.location.href = 'FAPI_LogEvent' + text; } function flurrySetUserID(userID) { window.location.href = 'FAPI_SetUserID' + userID; } Next, in Objective-C, you would implement the shouldStartLoadEvent and "capture" these href navigations, and tell the browser not to load them. You will need to split the string up yourself and call the appropriate function. Here's some code: - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType () { NSString *theAnchor = [[request URL] fragment]; if ([theAnchor hasPrefix:@"FAPI_LogEvent"]) { NSString *textToLog = [theAnchor substringFromIndex:[@"FAPI_LogEvent" length]]; [FlurryAPI logEvent:textToLog]; return NO; // prevent the UIWebView from navigating to this anchor } else if ([theAnchor hasPrefix:@"FAPI_SetUserID"]) { NSString *userID = [theAnchor substringFromIndex:[@"FAPI_SetUserID" length]]; [FlurryAPI setUserID:userID]; return NO; // prevent the UIWebView from navigating to this anchor } } The fact that the events are already defined in Objective-C doesn't really help much since you need to implement your own routing behavior to call the appropriate Objective-C method. The only way you could take advantage of the fact that the methods are already defined in Objective-C and avoid hard coding the routing logic, would be using @selectors or similar dynamic function calling which is available in Objective-C. However, this is much more complicated to implement and probably presents a security risk. I would recommend implementing the routing logic like is shown in the code above.

gnfti at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

PhoneGap has functionality for adding native plugins, to add a Flurry log event plugin for iOS I would do something like this: Add a PGFlurry PhoneGap plugin class: PGFlurry.h #import <PhoneGap/PGPlugin.h> @interface PGFlurry : PGPlugin - (void)logEvent:(NSArray*)arguments withDict:(NSDictionary*)options; @end PGFlurry.m #import "PGFlurry.h" #import "FlurryAPI.h" @implementation PGFlurry // if you init Flurry somewhere else you can remove this method - (PGPlugin*) initWithWebView:(UIWebView*)theWebView { self = [super init]; if (self == nil) { return nil; } // init and start Flurry [FlurryAPI startSession:@"API key"]; return self; } - (void)logEvent:(NSArray*)arguments withDict:(NSDictionary*)options { [FlurryAPI logEvent:[arguments objectAtIndex:0]]; } @end Add a JavaScript plugin helper to the www folder: Flurry.js PhoneGap.addConstructor(function() { if(!window.plugins) { window.plugins = {}; } window.plugins.flurry = { logEvent: function(name) { return PhoneGap.exec("PGFlurry.logEvent", name); } } }); Add the plugin to PhoneGap.plist by adding a key/value pair with both the key and value being "PGFlurry" to the "plugins" dictionary. Now you should be able to use it like this: <!DOCTYPE html> <html> <head> <script src="phonegap.js" type="text/javascript"></script> <script src="flurry.js" type="text/javascript"></script> <script type="text/javascript"> document.addEventListener("deviceready", function() { window.plugins.flurry.logEvent("Testing"); }, false); </script> </head> <body> </body> </html>

Mattias Wadman

You can find the Phonegap Flurry Plugin written by me at https://github.com/designerkamal/Phonegap-Flurry-Plugin

Kamal J

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.