Thursday, 5 June 2014

GoogleAnalytics from Developers Perspective (part2)

 

Once your tracking Id gets created (read Google Analytics – part 1), next step is to integrate this tracking Id in our code so that our events and screens got tracked as and when needed.

Setting Up the Google Analytics SDK

Download latest version of Google analytics sdk from  
https://developers.google.com/analytics/devguides/collection/ios/resources

Once downloaded unzip file, you will see following files in library folder:
GAI.h
GAITracker.h
GAITrackedViewController.h
GAIDictionaryBuilder.h
GAIFields.h
GAILogger.h

Add this files into your app. Select libGoogleAnalyticsServices.a and drag it into frameworks, You can place it anywhere inside your project, but it’s best to keep all of your frameworks in one place.

Next add the CoreData framework. Select your project file in the Project Navigator and then select Build Phases. Expand the Link Binary With Libraries section and click the add (+) button.
Add frameworks :
CoreData.framework
SystemConfiguration.framework
libz.dylib
 Your Google Analytics SDK integration is done.

Integrating Tracking Id in code:
Once you will create your tracking Id .Do following code in didFinishLaunchingWithOptions method:

You need to import  "GAI.h" and "GAITracker.h" in AppDelegate.m file.
The specific behavioral flags you are going to set are:
trackUncaughtExceptions – Tracking uncaught exceptions will flag up any exceptions that you are not dealing with that have caused your application to crash.
logLevel – Google Analytics iOS SDK has 4 logging levels: kGAILogLevelError, kGAILogLevelWarning, kGAILogLevelInfo, and kGAILogLevelVerbose. Verbose logging enables all of the various types of log output and prints it to the console in Xcode. This is extremely useful when you first start using Google Analytics for iOS as it lets you see what is going on under the hood.
dispatchInterval – By default, this is set to 120, which states that tracking information should be dispatched (uploaded to Google Analytics) automatically every 120 seconds. In this tutorial you will set this to a shorter time period so that you can see the data in your Google Analytics dashboard without having to wait for a prolonged period of time. In a production environment every 120 seconds should be often enough.

Screen tracking
Screens in Google Analytics represent content users are viewing within your app.
A screen view consists of a single string field that will be used as the screen name in your Google Analytics reports:


Manual Screen measurement: While automatically recording screen views can be convenient, it is not always possible or desirable to extend the built-in GAITrackedViewController.
To manually send a screen view, set the screen field values on the tracker, then send the hit:





 
Automatic Screen Measurement: Automatically measure views as screens using the GAITrackedViewController class. Have each of your view controllers extend GAITrackedViewController and add a property called ‘screenName’. This property will be used to set the screen name field.
Within this method a lot of things are at work the parent viewController will:
1.                       Get the shared instances’ Default Tracker setup with your tracking ID.
2.                       Tell the tracker that it’s tracking the “Home” screen.
3.                       Generate a logging entry containing the time and other information.
4.                       Use the Default Tracker object to publish that to the Google Analytics servers for visual exploration. Since we have configured the logging level to output verbose logging you will also see this output to the console.


Event Tracking 
 Events are a useful way to collect data about a user's interaction with interactive components of your app, like button presses or the use of a particular item in a game.
An event consists of four fields that you can use to describe a user's interaction with your app content:


Code that you have to integrate in your app is given below:
  
Custom Dimensions
One problem that we have faced in our app is that we need to track screens with respect to some group Ids of user. As the normal screen tracking will not give us flexibility to track screen category wise. We decided to use custom dimensions. To create custom dimension you can refer my blog – Google Analytics – Part 1.
Here I will tell you how to integrate code to track custom created dimensions. Add following code 

 
Custom dimension values can be sent with any Google Analytics hit type, including screen views, events, ecommerce transactions, user timings, and social interactions.
Custom dimensions consist of two fields:
·                          NSNumber Index – the index of the custom dimension. This index is 1-based.
·                          NSString Value – the value of the custom dimension.
For example, in our application we did following code to track screens group wise


Custom Metrics
To set and send a custom dimension value:



Custom dimension values can be sent with any Google Analytics hit type, including screen views, events, ecommerce transactions, user timings, and social interactions. The defined scope of the custom dimension will determine, at processing time, which hits are associated with the dimension value.

Session tracking
A session represents a single period of user interaction with your app. Session can only be managed manually.
Manual session measurement: 



Using multiple trackers
It is possible to use multiple trackers in your app. This can be useful for sending data to different Google Analytics properties associated with the same app. For example, maybe you have one property set up for your marketing team, who require information about how the app is being used, and another set up for your development team, who are looking at problem areas.
Setting up multiple trackers is as simple as initializing trackers with different property IDs:



By default, the first tracker initialized becomes the default tracker made available through the GAI shared instance. You have seen how to access this previously.
If you want to change the default tracker you can override it like so: 


Sampling Rate: Avoiding Inconsistencies
Sampling in Google Analytics or in any analytics software refers to the practice of selecting a subset of data from your data set and reporting on the trends available in that sample set.  Sampling speeds up processing for reports when the volume of data is so large as to slow down report queries. This is important if your user-base is extremely large.

To ensure that your tracker is sampling data consistently you should maintain a constant sample rate for each version of the app you release. Updating the tracker with the current version number is easy: add the following code to your AppDelegate:

 This code will fetch the current app version from your Xcode Info.plist file automatically and set it to the tracker object. It then sets a 50% sampling rate. Change version number and track your data

Ecommerce Tracking:
Use Ecommerce reporting to identify your best-selling products and most powerful promotions. You'll see what customers buy and how they do it, whether with complex transactions or one-click purchases. Trace transactions right down to specific keywords, understand shopper behaviors, and adjust your shopping cart to build loyalty and sales.
There are three steps to measure a transaction with Google Analytics:
1.                       Build a transaction object.
2.                       Build item objects and add them to the transaction object.
3.                       Send the transaction using sendTransaction:.
In the following example, we assume that onPurchaseCompleted is called after the user has completed an in-app purchase.

Parameters
TRANSACTIONID Optional Order ID of the transaction to associate with item.
SKU Required. Item's SKU code.
NAME Required. Product name. Required to see data in the product detail report.
CATEGORY Optional. Product category.
PRICE Required. Product price.
QUANTITY Required. Purchase quantity.
AFFILIATION Optional. Partner or store affiliation (undefined if absent).
TOTAL Required. Total dollar amount of the transaction. Does not include tax and shipping and should only be considered the "grand total" if you explicity include shipping and tax.
TAX Optional. Tax amount of the transaction.
SHIPPING Optional. Shipping charge for the transaction.

That all from my end, I will keep on adding new things in the blog as and when I have something new on Google Analytics in my bucket.

Happy Coding!!











Thursday, 29 May 2014

Asset Catalogs


 

What is Asset Catalog?

Use asset catalogs to simplify management of images that are used by your app as part of its user interface.
Basically you don’t see a large bulk of images in your project navigator and searching any image folder wise one by one.
One more thing to notice, right click on image set/Asset Catalog and click ‘Show in finder’. In the project navigator you will find a asset folder corresponding to each images having 1x, 2x and contents.json file, describing each image. That file is automatically created by Xcode.

Types of Assets
There are three types of assets that can be included in an iOS asset catalog:
App icons - App icon sets contain the icons that are displayed on the iOS Home screen, Spotlight search results, the Settings App, and in the App Store.
Launch images - Launch image sets contain all the versions of the launch image displayed at startup for all of the targeted iOS devices.
Image sets - Image sets contain all the versions of an image that are necessary to support all of the targeted iOS devices. This includes images used in table views, tab bars, image views, and so on.

Why to use it?

There are some advantages of using asset catalogs:
1.)         One of the primary reasons for using asset catalogs is to make it easier to manage your app's images.
Suppose if your app supports both retina and non-retina devices. You need two version of your graphics 1x and 2x and need to maintain naming convention like, for icon it would be icon.png and icon@2x.png. With asset catalog you no longer need to maintain this convention.
2.)         A second advantage of using asset catalogs is performance. If your project has an iOS 7 deployment target, Xcode compiles your asset catalogs into a runtime binary file format that improves the speed of your app.
3.)          It also alleviates the need to keep the naming in sync since they share one name.

How to create and access it?

App Icons and Launch Image: Whenever you create a new project with iOS 7 as deployment target, you will get a folder in your project navigator named ''. This is where your App icons and launch images resides. Tap on it you will get something like this:



Now go to targets of App, At the bottom of the Project Editor, you should see the App Icons and Launch Images section.


 
Under App Icons, there are three sets of images—App, Spotlight, and Settings that indicate where each set of icons is used. The Kind column specifies the device and operating system for which a particular icon is used. The Dimensions column specifies the required size of the icon. The Resource column is intended to show the image included in your project that fits the criteria in the Dimensions column. The No image with correct dimensions found warning is incorrect, since our sample project does contain several of the required icons.
In the Launch Images section, there is a list of launch images for the iPhone.

To add an asset catalog for app icon and launch images, tap on  ‘Use Asset Catalog button’ at the top. It will display a pop up like this:



Tap on migrate, now your app will use images present in your ‘Images.xassets’ folder. Your view will get now updated to




Tap on Arrow on side of AppIcon/LaunchImage, you will get directed to asset catalogs folder.


Creating Asset Catalogs: For appicon and launch images we have built in asset folder, but what for other images that we are using in our app. Adding this images files to your create a bulk of images in project navigator, in that case if you want to search for a particular folder you have to open each and every folder until you are so sure where the image exactly resides.

Creating Asset catalog escape us from doing this:

Steps:
1.) Choose File > New > File.
2.) Under iOS or OS X, select Resource.
3.) Select Asset Catalog, and click Next.


4.)         Name the asset catalog, specify its location, and select the targets.



5.)         Click Create.

Your asset catalogs gets created. This newly asset catalog is empty for now.

Now it’s your choice, do you want to maintain images folder wise?
Or, want to add all images without maintaining folder structure?
Or, want to create separate asset catalog?

Here I will tell you how to maintain images folder wise?
Steps:
1.)         Tap on plus(+) sign at the bottom left corner or right click



2.)         Select ‘New Folder’
3.)         Your new folder gets created. Now Select that folder and right on it


4.)         Tap on ‘New Image Set
5.)         Double tap on the name of folder and image set to rename it. (Renaming image set is important as we will be accessing our images by this name only)


6.)         If your images not already added to your project just drag and drop your images to the block 1x and 2x,your images get added to your project. Alternatively, if you already added those images in your project, you need to import those files.





Accessing Asset Catalog: Accessing catalogs is same as you are accessing your images with ‘ImageNamed’. To load an image from an asset catalog, you can call the UIImage:imageNamed: method, passing the name of the set that contains the image.

For example, if your images set is named as ‘Search, you will access this search images using [UIImage imageNamed:“Search”]


Customizing Sets

Select a image set you want to customize and do customization like you can change name of your image set or make your images device specific.



Removing catalogs, or imagesets, or Folders
To remove a catalog, right click on that catalog and select ‘Delete’ option.
For imagesets or Folders, right click or control click on that folders, you will get option ‘Remove Selected Items’.



Disadvantages: Some few disadvantages when we implement asset catalog to manage our images are:
1.) You can no longer Command-Shift-O to look for an image.
2.) Another little annoyance is that Test Flight still wants to see an Icon.png file in your uploaded apps. The only way around it is to include a separate icon image in Xcode and add an icon entry back into the plist.

But as these advantages are not bigger than your App performance, I would recommend to use asset catalogs.

Happy Coding!!