Cannot get Google Analytics API to register page views on iPhone - iphone

I would like to gather usage statistics for my iPhone app using Google Analytics so I'm trying to configure it using the following tutorial: http://code.google.com/intl/fr-FR/apis/analytics/docs/tracking/mobileAppsTracking.html
I think I did everything they indicate in the documentation, and I get no error on the iPhone side, but I don't see any visits in Google Analytics.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
[self initGoogleAnalytics];
//...
}
-(void)initGoogleAnalytics{
[[GANTracker sharedTracker] startTrackerWithAccountID:[[NSBundle mainBundle] objectForInfoDictionaryKey:#"GoogleAnalyticsCode"]
dispatchPeriod:-1
delegate:nil
NSError *error;
if(![[GANTracker sharedTracker] trackPageview:#"/home" withError:&error]){
NSLog(#"%#", [error localizedDescription], nil);
}
[[GANTracker sharedTracker] dispatch];
}
Any idea why this is not working?

this is the same answer that I put at: Problem dispatching with google mobile analytics for iphone
The Google Analytics stop sending data when you try to send a non formatted "URL", if it is not initiated with the "/" or contain some specific chars, it will start only returning errors.
The best thing to do is, verify that you are placing the "/" on the beginning of you URL and before sending, format your URL to avoid any problem, by doing:
NSString* pageURLString = [pageURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
Encoding it with NSASCIIStringEncoding, will format the URL properly. The same can be used when tracking an event.

Related

Google Analytics Integration issues

I am not sure I fully understand the Google Analytics integration. At least, what I read on Google's SDK Page and what I see in reality are not the same.
I've setup the Tracker in my applicationDidFinishLaunching method, with my key.
[[GANTracker sharedTracker] startTrackerWithAccountID:#"UA-xxxxxxxx-1"
dispatchPeriod:30 // SENDS EACH 30 SECONDS.
delegate:self];
NSError *error;
if (![[GANTracker sharedTracker] setCustomVariableAtIndex:1
name:#"iPhone"
value:appVersion
withError:&error]) {
// Handle error here
ALog("Google Analytics Error: %#", error);
}
if (![[GANTracker sharedTracker] trackPageview:#"/app_did_finish_Launching"
withError:&error]) {
// Handle error here
ALog("Google Analytics Error:%#", error);
}
I am using a delegate to ensure that the dispatch is firing, and it is, and each time it says it is successful.
- (void)trackerDispatchDidComplete:(GANTracker *)tracker
eventsDispatched:(NSUInteger)eventsDispatched
eventsFailedDispatch:(NSUInteger)eventsFailedDispatch {
DLog(#"events dispatched: %d, events failed: %d", eventsDispatched, eventsFailedDispatch);
}
Question 1:
I am trying to see this over WIFI, with a proxy I've setup between my iPhone and the web. I see nothing that looks like Google analytics traffic. Should I expect to see anything?
Question 2:
Its been 24 hrs, and I don't see anything on the Google Analytics site. Should I see something? I've had success with this implementation only when I set the dispatchPeriod to 0, and manually call dispatch in the code.
BOOL success = [[GANTracker sharedTracker] dispatch];
But I really don't want to do this in a shipping app version.
What am I doing wrong? Do I need to call dispatch manually? The SDK implied you only call the dispatch if you want to send it manually (without batching the sends). Am I understanding this correctly?
Thanks for your help.
-Yenyi
Well, it takes a long time to update. More than 24 hrs. But it does update. In the end, decided to go with Flurry, the API was just cleaner.

iPhone Google Analytics SDK delegate and multiple accounts problem

I am implementing google Analytics SDK in my iPhone application. I had it working with following code:
AppDelegate .m :
[[GANTracker sharedTracker] startTrackerWithAccountID:#"UA-xxxxxxx-1"
dispatchPeriod:10
delegate:nil];
if (![[GANTracker sharedTracker] trackPageview:string withError:&error]) {
NSLog(#"Error happened with google analytics tracking 2, %#", error);
}else {
NSLog(#"OK");
}
In my analytics account I was getting the wanted results. Then I decided (don't ask me why) to try to send my tracking data to 2nd analytics account too. For curious ones: One account is used for web page and iPhone app stats and the other one is supposed to be just for iPhone.
My ingenious plan was to create 1st sharedTracker, dispatch it, stop it and do the same for the second one:
AppDelegate .h:
#interface AppDelegate : NSObject <UIApplicationDelegate, GANTrackerDelegate>
//implementation
AppDelegate .m:
//1st tracking account
[[GANTracker sharedTracker] startTrackerWithAccountID:#"UA-xxxxxxx-1"
dispatchPeriod:10
delegate:self];
if (![[GANTracker sharedTracker] trackPageview:string withError:&error]) {
NSLog(#"Error happened with google analytics tracking, %#", error);
}else {
NSLog(#"1. GAnalytics: OK");
}
[[GANTracker sharedTracker] stopTracker];
//2nd tracking account
[[GANTracker sharedTracker] startTrackerWithAccountID:#"UA-zzzzzzzz-1"
dispatchPeriod:10
delegate:self];
if (![[GANTracker sharedTracker] trackPageview:string withError:&error]) {
NSLog(#"Error happened with google analytics tracking, %#", error);
}else {
NSLog(#"2. GAnalytics: OK");
}
[[GANTracker sharedTracker] stopTracker];
- (void)trackerDispatchDidComplete:(GANTracker *)tracker
eventsDispatched:(NSUInteger)eventsDispatched
eventsFailedDispatch:(NSUInteger)eventsFailedDispatch{
NSLog(#"For the love of Got, why don't you say something?");
}
I added the delegate method in order to get some clue what's being dispatched, and to find out if SDK is making two different requests, but it seems I can't get my delegate method invoked!
Removing the second tracker's code doesn't help either
I also tried putting the dispatch period to 0 (and -1 with manual dispatch call) but I had no luck with this either…
So, my questions are:
how to implement 2 gAnalytics accounts and
how to make my delegate method do what it's supposed to do - get called after dispatch :)
Thanks in advance,
Luka
I started out exactly with the same requirement of being able to post pageviews, events etc onto two different Google Analytics accounts. But the problem is that, [GANTracker sharedTracker] is a singleton object and you always get the same or single instance of the object back, so you cannot really have two instances of the sharedTracker.
Also in your case, where you are trying to see whether the call back method is called, it will not be called because you are calling [[GANTracker sharedTracker] stopTracker] and this will prevent from dispatch of the events to happen. If you comment out that line, your callback method should get called.
If you look in the app directory under Documents, Google analytics stores all the data in a sqlite database called googleanalytics.sql. You can open it and see the tables in it. Go to that directory and type "sqlite3 googleanalytics.sql" and if you know sqlite commands, you can navigate the tables and stuff. None of the tables have a reference to the Account ID, so my guess is that, unless you do some really smart quirks, you cannot really post to two different Accounts.
Google has support for using multiple tracking accounts in the same application, in its iOS SDK v2
See this SO question and my answer there.

iPhone App Google Analytics

I am having issues setting up Google Analytics for my iPhone Application. I have a website that I have sucesfully been using Google Analytics on, and so I am pretty familiar with how it works.
I set up a new fake domain with the following formation: myapp.mysite.com. I got the UA ID that was made and used that as shown below.
In my iPhone application's "didfinishlaunching" method, I have the following code:
[[GANTracker sharedTracker] startTrackerWithAccountID:#"UA-XXXXXXXX-X"
dispatchPeriod:kGANDispatchPeriodSec
delegate:nil];
NSError *error;
if (![[GANTracker sharedTracker] trackEvent:#"test" action:#"my_action" label:#"my_label" value:-1 withError:&error]) {
NSLog(#"error ocurred");
}
where UA-XXXXXXXX-X is filled in with my ID.
I install the application on my phone, run the app for over 20 minutes, and google analytics still states that "tracking is not installed."
What is wrong here?
Thanks!
Here are a few things to try:
First, try adding
BOOL success = [[GANTracker sharedTracker] dispatch];
to the end of your code and testing the value of success.
Second, I don't see kGANDispatchPeriodSec defined in GANTracker.h. Is this a const that you're creating? Pass in a 0 as the dispatchPeriod instead so dispatches are sent immediately instead of batched. (You'll want to change this before you submit your app.)
Finally, implement GANTrackerDelegate on your class and see what's happening in the trackerDispatchDidComplete:eventsDispatched:eventsFailedDispatch call. This will tell you if your dispatch calls are failing, but unfortunately won't tell you why.
See this link about adopting a protocol on your class. In your .m file, add the following:
#pragma mark GANTrackerDelegate
- (void)trackerDispatchDidComplete:(GANTracker *)tracker
eventsDispatched:(NSUInteger)eventsDispatched
eventsFailedDispatch:(NSUInteger)eventsFailedDispatch {
NSLog(#"events dispatched: %d, events failed: %d", eventsDispatched, eventsFailedDispatch);
}

iphone nsurlconnection read cookies

I am using async NSURLConnection to connect to a web site from iPhone. Handle didReceiveResponse is activated on response and I am trying to get all cookies, by using allHeaderFields from NSHTTPURLResponse
I see many hreader, but no Set-Cookie - it looks like iphone simulator just ignores them...
And I am sure cookies are present in response - network monitor shows they present
I do not use any http storage - all that I am trying to do is to print to log all header - and do not see cookies info
Does anybody know about this issue?
UPDATE
I have made some research: if my website returns custom header, like "Custom-Header: value" - then this header is visible in java client, but is not in iphone...
thanks
Try to look for it in the shared HTTP cookies storage:
for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies])
{
NSLog(#"name: '%#'\n", [cookie name]);
NSLog(#"value: '%#'\n", [cookie value]);
NSLog(#"domain: '%#'\n", [cookie domain]);
NSLog(#"path: '%#'\n", [cookie path]);
}
or if working in Swift:
for cookie in HTTPCookieStorage.shared.cookies!
{
NSLog("name: \(cookie.name)")
NSLog("value: \(cookie.value)")
NSLog("domain: \(cookie.name)")
NSLog("path: \(cookie.path)")
}
Try this: in your NSMutableURLRequest, you should tell it to handle cookies:
[request setHTTPShouldHandleCookies:YES];
I don't know if it matters in apps, but what is your Accept Cookies setting for Safari in the Settings app. See if changing to Always matters.
According to some sites I've seen, a complete reboot of the iPhone is required for this setting to have any effect.

Reading cookies using xcode on the iphone [duplicate]

Can an iPhone application read cookies previously stored by Safari Mobile?
To actually answer your question:
No.
Mobile Safari's cookies are not accessible from SDK apps. And each SDK app is given its own WebKit cache and cookie stores, so while cookies will persist within the same app, they aren't accessible betweeen apps.
As of iOS 9 this is possible!
Use a sfSafariViewController.
You will need to setup:
A custom URL scheme in your app to receive cookie data.
The website you are getting cookies from will need to implement an API specific your app's custom URL scheme, to redirect back to your app.
You can clone this repo which has a fully working demo of this.
Hope this helps,
Liam
There is actually an interesting way if you have access to a server url.
In your app launch the server url with mobile safari.
The target server url reads the cookie and redirects back to an app specific url (myapp://cookie=123)
The app is then switched back and you can read that value from the url handler
It's a little hacky as the app would switch mobile safari and then immediately switch back to the app. But, it is possible.
Note that on iOS 8, you're probably better using Safari Password Sharing to solve some of the use cases that give rise to this problem.
This is not directly possible, but with the cooperation of the web site it is possible.
To clarify, the user case is that an Objective C application wants to read the value of a cookie that has been set by a website in mobile safari. (ie. in particular, a UIWebView was not involved in setting the cookie)
Your app should do this:
Launch mobile safari, using [[UIApplication sharedApplication] openURL:url];
The URL should be a special one, eg. http://yourwebsite.com/give-ios-app-the-cookie
On your website, when that url is launched, issue a redirect to your-app-url-scheme:cookievalue= (eg. angrybirds:cookievalue=hh4523523sapdfa )
when your app delegate receives - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation process the url to get the cookie value
Note that you should not do this automatically when the application starts - the user will see the transfer to Mobile Safari and back, which is not a good user experience and Apple will reject your app (Apple also consider this to be "uploading user's personal data to server without their prior consent"). It would be better to do it in response to the user, paying attention to the user experience - eg. wait for the user to hit a "login" button, then do it, and if the user is not logged into your website, http://yourwebsite.com/give-ios-app-the-cookie should show the user the login screen within safari. If the user is logged in you could briefly show a "Automatically logging you in..." screen for a second or two in Safari before redirecting the user back.
There's no way to get this to work with hotmail/gmail/etc of course - it needs to be your own website.
Credit goes to Unique Identifier for both mobile safari and in app in iOS for suggesting this kind of approach.
Because of sandboxing on the iPhone you don't have access to Safari's cookies. You can only access cookies created within your application - by an UIWebView for example.
Although you have asked the same question twice before, here's one approach not yet mentioned...
This may be a little convoluted, but you can do Greasemonkey-esque things with a UIWebView. Something like this:
Load your target page
craft some javascript which will read the document.cookie and return the data you need
In the webViewDidFinishLoad delegate, inject this javascript into the UIWebView with the stringByEvaluatingJavaScriptFromString message
I've used this technique to enhance 3rd party pages in an iPhone app, but I'm not sure if it will read cookies from the same place as Safari mobile.
Worth a shot though?
Here's my utils get/set cookie methods.
+(void)setCookie:(NSString *)key withValue:(NSString *)value {
NSArray *keys = [NSArray arrayWithObjects:
NSHTTPCookieDomain,
NSHTTPCookieExpires,
NSHTTPCookieName,
NSHTTPCookiePath,
NSHTTPCookieValue, nil];
NSArray *objects = [NSArray arrayWithObjects:
#"YOURDOMAIN",
[NSDate distantFuture],
key,
#"/",
value, nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:dict];
NSHTTPCookieStorage *sharedHTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
[sharedHTTPCookieStorage setCookie:cookie];
}
+(NSString *)getCookie:(NSString *)key {
NSHTTPCookieStorage *sharedHTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray *cookies = [sharedHTTPCookieStorage cookiesForURL:[NSURL URLWithString:#"YOURDOMAIN"]];
NSEnumerator *enumerator = [cookies objectEnumerator];
NSHTTPCookie *cookie;
while (cookie = [enumerator nextObject])
{
if ([[cookie name] isEqualToString:key])
{
return [cookie value];
}
}
return nil;
}
You might want to check
if ([[NSHTTPCookieStorage sharedHTTPCookieStorage] cookieAcceptPolicy] != NSHTTPCookieAcceptPolicyAlways) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
}
But apparently NSHTTPCookieStorage does not even hold cookies from the last request in the current application on iOS (rdar://8190706)