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

前端 未结 4 1266
太阳男子
太阳男子 2021-01-25 03:21

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         


        
4条回答
  •  臣服心动
    2021-01-25 03:48

    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 
    
    @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:

    
    
      
        
        
        
      
      
      
    
    

提交回复
热议问题