Skip to content

Instantly share code, notes, and snippets.

@vladignatyev
Last active March 28, 2016 17:24
Show Gist options
  • Save vladignatyev/c240a1a4867b17894b10 to your computer and use it in GitHub Desktop.
Save vladignatyev/c240a1a4867b17894b10 to your computer and use it in GitHub Desktop.
Add Google Analytics into XCode project for iOS, resolving "use of '@import' when modules are disabled” error
//
// APAnalyticsTracker.h
#import <Foundation/Foundation.h>
@interface APAnalyticsTracker : NSObject
+ (void)configureTracker;
+ (void)trackScreenWithName: (NSString*) name;
+ (void)trackEventWithCategory: (NSString*) category
action: (NSString*) action
label: (NSString*) label;
+ (void)trackEventWithCategory: (NSString*) category
action: (NSString*) action
label: (NSString*) label
value: (NSNumber*) value;
@end
//
// GBAAnalyticsTracker.m
#import "APAnalyticsTracker.h"
#import "Google/Analytics.h"
@implementation APAnalyticsTracker
+ (void)configureTracker
{
// Configure tracker from GoogleService-Info.plist.
NSError *configureError;
[[GGLContext sharedInstance] configureWithError:&configureError];
NSAssert(!configureError, @"Error configuring Google services: %@", configureError);
// Optional: configure GAI options.
GAI *gai = [GAI sharedInstance];
gai.trackUncaughtExceptions = YES; // report uncaught exceptions
#if !(RELEASE)
gai.logger.logLevel = kGAILogLevelVerbose; // remove before app release
#endif
}
+ (void)trackScreenWithName: (NSString*) name
{
id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
[tracker set:kGAIScreenName value:name];
[tracker send:[[GAIDictionaryBuilder createScreenView] build]];
}
+ (void)trackEventWithCategory: (NSString*) category
action: (NSString*) action
label: (NSString*) label
{
[self.class trackEventWithCategory:category action:action label:label value:@1];
}
+ (void)trackEventWithCategory: (NSString*) category
action: (NSString*) action
label: (NSString*) label
value: (NSNumber*) value
{
id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
[tracker send:[[GAIDictionaryBuilder createEventWithCategory:category
action:action
label:label
value:value] build]];
}
@end
//
// In your AppDelegate.mm
#import "APAnalyticsTracker.h"
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[APAnalyticsTracker configureTracker];
// ...
}
//
// In every View Controller you'd like to track
#import "APAnalyticsTracker.h"
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[APAnalyticsTracker trackScreenWithName:@"This screen name"];
// ...
}
//
// Wherever you're going to track some events
#import "APAnalyticsTracker.h"
- (void)userBought10Whiskey
{
// ...
[APAnalyticsTracker trackEventWithCategory:@"User events"
action:@"Purchased 10 wiskey"
label:@"10 wiskey has been purchased"
value:@10];
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment