Search code examples
iosswiftgoogle-analyticsgoogle-analytics-firebasegoogle-analytics-sdk

What is the proper syntax for Google Analytics Exception tracking in Swift?


I'm trying to use Exception Tracking for my app in Google Analytics. https://developers.google.com/analytics/devguides/collection/ios/v3/exceptions

I am just trying to figure out the syntax for this in Swift (not super familiar with Obj-C):

@try {
    // Request some scores from the network.
    NSArray *highScores = [self getHighScoresFromCloud];
}
@catch (NSException *exception) {
    // May return nil if a tracker has not already been initialized with a
    // property ID.
    id tracker = [[GAI sharedInstance] defaultTracker];
    [tracker send:[[GAIDictionaryBuilder
        createExceptionWithDescription:@"Connection timout %d: %@", connectionError, errorDescription  // Exception description. May be truncated to 100 chars.
    withFatal:@NO] build]];  // isFatal (required). NO indicates non-fatal exception.
}

I have set up my tracker okay, and it is working fine saving other data to GA, it is just the syntax calling createExceptionWithDescription() in Swift that I'm not certain of.

There sure doesn't appear to be much in the way of examples / docs for using Swift for Google Analytics... =/ If you know of any, please let me know!

Thanks.


Solution

  • I'd imagine its something along the lines of:

    let dictionaryToSend = GAIDictionaryBuilder.createExceptionWithDescription("Connection timeout \(connectionError): \(errorDescription)", withFatal: NSNumber(bool: false)).build()
    

    If its a class function in Obj-C written like

    [GAIDictionaryBuilder createExceptionWithDescription:...]; // objc

    Its written like

    GAIDictionaryBuilder.createExceptionWithDescription(...); // swift

    Each of the colons in obj-c denotes an argument variable.

    // Broken into two lines to make it easier to read
        [GAIDictionaryBuilder createExceptionWithDescription: @"String here"
                              withFatal: @NO]; 
    

    You can do a similar thing in swift:

    //Comma separated 
        GAIDictionaryBuilder.createExceptionWithDescription("Description String",
                                                            withFatal: NSNumber(bool:false));
    

    I suggest you learn a little bit of the ObjC messaging syntax since a lot of iOS code is still in ObjC but don't worry a huge amount about it. Swift is a better language.