Google Analytics crash with Swift 2.0 - ios

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")
}
}

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.

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)

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)")

Related

nil value returned by NSClassFromString swift 2.0

I'm using the following code in my project to draw fading on a view:
let customBlurClass: AnyObject.Type = NSClassFromString("_UICustomBlurEffect")!
let customBlurObject: NSObject.Type = customBlurClass as! NSObject.Type
self.blurEffect = customBlurObject.init() as! UIBlurEffect
self.blurEffect.setValue(1.0, forKeyPath: "scale")
self.blurEffect.setValue(radius, forKeyPath: "blurRadius")
super.init(effect: radius == 0 ? nil : self.blurEffect)
sometimes on Fabric I get crash report from the app on this line:
let customBlurClass: AnyObject.Type = NSClassFromString("_UICustomBlurEffect")!
which means that the NSClassFromString return nil value,
I searched a lot about this problem but no useful answers,
Please Help,
Thanks.
The most likely explanation is that those crashes occur on devices running iOS 8 or earlier. _UICustomBlurEffect was introduced in iOS 9.
You should do:
if let blurClass = NSClassFromString("_UICustomBlurEffect") {
// set up blur view
}
to avoid crashes on devices where it's not supported.

When adding do,try catch Google Analytic tracker got error

I still can't figure my simple do,try catch at json parsing causing google analytic compile time error.
Especially at theses :
let tracker = GAI.sharedInstance().defaultTracker
let event = GAIDictionaryBuilder.createEventWithCategory("Home Screen", action: "Tapped", label: "User tapped one of content from Home Content Area 2", value: nil)
tracker.send(event.build() as [NSObject : AnyObject]) // Show me error at this
All I did was adding my do,try catch at RequestSuccess[When getting response from server,parse json to model object] delegate method.
Any Help,do I need to add some info extras?
When I remove do,try,catch,that error gone.Do my do,try,catch concern with that error?
It's not obvious, but I don't think the do, try, catch is the issue. Try:
tracker.send(event!.build() as [NSObject : AnyObject])
You may also need to unwrap the tracker with tracker?.send... etc.

XCode Errors on bridged AWS SDK

I'm pretty new to iOS and 100% new to AWS. I'm building an app that needs to upload files. I downloaded the Amazon SDK through CocoaPods and used a bridging header to work with it in Swift.
Here's my header:
#ifndef ObjC_Bridging_Header_h
#define ObjC_Bridging_Header_h
#import "AWSCore.h"
#import "AWSS3.h"
#import "AWSDynamoDB.h"
#import "AWSSQS.h"
#import "AWSSNS.h"
#import "AWSCognito.h"
#endif /* ObjC_Bridging_Header_h */
I pointed to that file in my build settings to tell the compiler where it was.
Then I tried to configure the SDK in my AppDelegate.swift with this code:
var window: UIWindow?
let cognitoAccountId = "I'm not going to post this"
let cognitoIdentityPoolId = "I'm not going to post this"
let cognitoUnauthRoleArn = "I'm not going to post this"
let cognitoAuthRoleArn = "I'm not going to post this"
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let credentialsProvider = AWSCognitoCredentialsProvider.credentialsWithRegionType(
AWSRegionType.USEast1,
accountId: cognitoAccountId,
identityPoolId: cognitoIdentityPoolId,
unauthRoleArn: cognitoUnauthRoleArn,
authRoleArn: cognitoAuthRoleArn)
let defaultServiceConfiguration = AWSServiceConfiguration(
region: AWSRegionType.USEast1,
credentialsProvider: credentialsProvider)
AWSServiceManager.defaultServiceManager().setDefaultServiceConfiguration(defaultServiceConfiguration)
return true
}
(And yes, I put in all of the ID strings etc. I just didn't want to post them)
Everything works except this last line:
AWSServiceManager.defaultServiceManager().setDefaultServiceConfiguration(defaultServiceConfiguration)
It errors saying:
"Value of type 'AWSServiceManager' has no member 'setDefaultServiceConfiguration'"
Why is everything working except for this line? What's wrong?
AWSServiceManager has no setter for defaultServiceConfiguration.
Instead you have to use
AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = defaultServiceConfiguration
This'll work.

Google Analytics not tracking in Swift

I'm trying to get Google Analytics to run in my Swift project. I'm following this tutorial: https://developers.google.com/analytics/devguides/collection/ios/v3/?ver=swift
It says i'm suppose to include it with #import <Google/Analytics.h> that seems to be objective-c though.. however i'm able to do: import Google
I download the GoogleService-info.plist and the it's target membership to my app.
Then i pasted this code:
// Configure tracker from GoogleService-Info.plist.
var configureError:NSError?
GGLContext.sharedInstance().configureWithError(&configureError)
assert(configureError == nil, "Error configuring Google services: \(configureError)")
// Optional: configure GAI options.
var gai = GAI.sharedInstance()
gai.trackUncaughtExceptions = true // report uncaught exceptions
gai.logger.logLevel = GAILogLevel.Verbose // remove before app releaseAppDelegate.swift
However i don't see any statistics for my app, is there anything i have done wrong or is additional work needed?
You also need to track an event. I think the above code is only for setting up GA in your app. For example, you can add the following code to one of your view controllers whose screen view you want to track :
let tracker = GAI.sharedInstance().defaultTracker
tracker.set("TEST", value: "TEST")
let builder = GAIDictionaryBuilder.createScreenView()
tracker.send(builder.build() as [NSObject : AnyObject])
And also keep in mind, that GA events sometimes take very long to show up on the live tracker in the dashboard.
Hope it helps!
var configureError: NSError?
GGLContext.sharedInstance().configureWithError(&configureError)
assert(configureError == nil, "Error configuring Google services: \(configureError)")
guard let gai = GAI.sharedInstance() else {
assert(false, "Google Analytics not configured correctly")
}
gai.trackUncaughtExceptions = true // report uncaught exceptions
gai.logger.logLevel = GAILogLevel.verbose // remove before app release
gai.dispatchInterval = 20
gai.tracker(withTrackingId: "UA-XXXXXXXX-X")
//Track an event
let tracker = GAI.sharedInstance().defaultTracker
let eventTracker: NSObject = GAIDictionaryBuilder.createEvent(
withCategory: YOUR_CATEGORY_NAME,
action: YOUR_ACTION_NAME",
label: YOUR_LABEL_NAME,
value: nil).build()
tracker?.send(eventTracker as! [AnyHashable: Any])

iOS Swift : error with google login

I was following this tutorial to add google sign in in my iOS app using swift. I followed all the steps as mentioned but when I try to build app then it is giving me an issue in my appdelegate.swift file.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
var configureError: NSError?
GGLContext.sharedInstance().configureWithError(&configureError)
assert(configureError == nil, "Error configuring Google services: \(configureError)")
GIDSignIn.sharedInstance().clientID = "client id"
return true
}
so below line of code
GGLContext.sharedInstance().configureWithError(&configureError)
Error text is "Use of unresolved identifier GGLContext". What could be the issue here ?
in Bridging-Header.h
import <GoogleSignIn/GoogleSignIn.h>
import <Google/Core.h>
in AppDelegate.swift
import Google
Preliminary:
I have been annoyed for a few days now that when I integrated the Cocoapod Google/SignIn that I was getting Thread warnings. After digging into everything, I may have found a solution. This probably would only be something worth looking at if the only aspect of google you want in your project in sign in. If you have Firebase or any other part of google integrated, you probably will never hit an issue that leads you to this thread though.
OK, after delving into this problem for a bit, I found my solution to be:
In Bridging Header import only #import <GoogleSignIn/GoogleSignIn.h>
In AppDelegate import only import GoogleSignIn
In Podfile import only pod 'GoogleSignIn'
In AppDelegate didFinishLaunchingWithOptions do domething like this:
if let path = Bundle.main.path(forResource: "GoogleService-Info", ofType: "plist"),
let googleInfo = NSDictionary(contentsOfFile: path),
let clientId = googleInfo["CLIENT_ID"] as? String {
GIDSignIn.sharedInstance().clientID = clientId
}
GIDSignIn.sharedInstance().delegate = self
and remove:
var configureError: NSError?
GGLContext.sharedInstance().configureWithError(&configureError)
assert(configureError == nil, "Error configuring Google services: \(configureError!)")
With this setup, everything seems to be working great. I got the idea by looking at the link below. Let me know if this works for you.
https://github.com/googlesamples/google-services/blob/master/ios/signin/SignInExampleSwift/AppDelegate.swift
I found the solution, You can use the Bridge-Header.h file and import like that
#ifndef Bridge_header_h
#define Bridge_header_h
#import "Google/Core.h"
#import "GoogleSignIn.h"
#endif /* Bridge_header_h */
it's work perfectly at my end.
in swift, the below worked for me.
import GoogleSignIn

Resources