ytpm
ytpm

Reputation: 5150

Google Analytics crash with Swift 2.0

I've just installed GoogleAnalytics from CocoaPods and tried to use it, suddenly it crashes with an error:

fatal error: unexpectedly found nil while unwrapping an Optional value

The crash occurs in this part:

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    let tracker = GAI.sharedInstance().defaultTracker
    tracker.set(kGAIScreenName, value: "Main")

    let builder = GAIDictionaryBuilder.createScreenView()
    tracker.send(builder.build() as [NSObject : AnyObject])
}

And when reaching this line:

tracker.set(kGAIScreenName, value: "Main")

Maybe it has something to do with the framework is bridged from Objective-C?


Update

So I fixed the crash by wrapping it with an if statment and still nothing sent to Google Analytics:

let name = "Main"
if let gai = GAI.sharedInstance() {
    if let tracker: GAITracker = gai.trackerWithTrackingId("TRACKING_ID") {
        tracker.set(kGAIScreenName, value: name)

        let builder = GAIDictionaryBuilder.createScreenView()
        tracker.send(builder.build() as [NSObject : AnyObject])

        print("tracker initialized")
    }
}

Upvotes: 2

Views: 964

Answers (3)

Guilherme Torres Castro
Guilherme Torres Castro

Reputation: 15350

For me I had to add those lines in the AppDelegate:

var configureError:NSError?
GGLContext.sharedInstance().configureWithError(&configureError)
assert(configureError == nil, "Error configuring Google services: \(configureError)")

Upvotes: 0

ytpm
ytpm

Reputation: 5150

So I figured out the problem, I used Google Analytics with CocoaPods as explained in the Google Analytics iOS tutorial and added this line to the Bridging Header file:

#import <Google/Analytics.h>

but I guess that's not enough, after adding these lines:

#import <GoogleAnalytics/GAI.h>
#import <GoogleAnalytics/GAIDictionaryBuilder.h>
#import <GoogleAnalytics/GAILogger.h>
#import <GoogleAnalytics/GAITrackedViewController.h>
#import <GoogleAnalytics/GAITracker.h>

It worked perfect. (Thanks Rich Tolley for the help)

Upvotes: 1

Rich Tolley
Rich Tolley

Reputation: 3842

The docs for the GAI class have this to say about defaultTracker

> For convenience, this class exposes a default tracker instance. This is initialized to nil and will be set to the first tracker that is instantiated in trackerWithTrackingId:. It may be overridden as desired.

So I'm guessing you need to call trackerWithTrackingId: somewhere, or if you are already doing it, make sure it happens before this method is called.

Upvotes: 1

Related Questions