Friday, April 22, 2016

Add Google Analytics to your iOS Apps

Google Analytics provides powerful information basing on the usage of your web application. It can also provide similar service to your mobile applications. Here's how you can do it:

Create mobile app GA account
  • In GA, go to Admin tab, click ACCOUNT drop down and select 'Create new account'. 
  • On New Account page, pick 'Mobile app'. Specify your account name, your app name, industry category etc.
  • Click on 'Get Tracking ID'
  • You can create multiple Tracking ID for the same mobile app by selecting 'Create new property' under 'PROPERTY' section

Add Google Analytics to iOS App

1. Install Google Analytics using CocoaPods:
  • If you haven't use pod for our current iOS app, open a terminal and cd to your Xcode project of your app, run: pod init to create a Podfile
  • Open Podfile, and add: pod 'Google/Analytics'
  • Now install pod by running this: pod install
  • As of now, it installs the following libraries:
    • Google (1.3.2)
    • GoogleAnalytics (3.14.0)
    • GoogleInterchangeUtilities (1.1.0)
    • GoogleNetworkingUtilities (1.0.0)
    • GoogleSymbolUtilities (1.0.3)
    • GoogleUtilities (1.1.0)  
2. Get Google Analytics configuration file:

  • On 'PROPERTY' section, select .js > Tracking Code
  • Then 'Getting started guide' link next to 'Google Analytics iOS SDK
     
  • It will take you to 'Analytics for iOS' page. Select which language you use for iOS development, for me I select Swift
  • Then click on 'GET A CONFIGURATION FILE' button, it looks like this:
    
  • It will bring you to this page. where you can: 
    • Specify your app name and iOS bundle ID
    • Choose and configure services (check Analytics)
    • Download generated GoogleService-Info.plist file
 3. Update your iOS app to include GA and configure GGLContext
  • Add GoogleService-Info.plist to your iOS app
  • Add #Import "Google/Analytics.h" to your app's Bridging-Header.h
  • Add GA related header files to your project
  • Override AppDelegate's didFinishLaunchingWithOptions to configure GGLContext:
   //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.
   let gai = GAI.sharedInstance()
   gai.trackUncaughtExceptions = true  // report uncaught exceptions
   gai.logger.logLevel = GAILogLevel.Verbose  // remove before app release

 4. Add screen tracking
  • In your major screen view controller, add tracking code to the end of its viewWillAppear method:
   let tracker = GAI.sharedInstance().defaultTracker
   tracker.set(kGAIScreenName, value: screenName)

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

 Verify tracking
  • Run your iOS app, navigate to screens with GA tracking code
  • In GA Real-Time, you should be able to see a screen view:)

Wednesday, March 23, 2016

Working with Microsoft Excel using C#

Library

To programmatically access MS Excel, you will need Microsoft Excel Extension library usually comes with Visual Studio: Microsoft.Office.Interop.Excel. I usually include it in header like this:

    using Excel = Microsoft.Office.Interop.Excel;

Open an Excel file
 
You can code like this:
  
  var app = new Excel.Application();
  var book = app.Workbooks.Open(fileName, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

Or simply like this:

     var book = app.Workbooks.Open(@"c:\test\data.xlsx");

Access a sheet, Range and cell

To access a sheet, say the first sheet (please note sheet index is 1-based rather than 0-based):

  var sheets = book.Worksheets as Excel.Sheets;
  var sheet = (Excel.Worksheet)sheets.get_Item(1);

To reach to a cell, you will do it through excel object Range, like this:

  var range = sheet.UsedRange;

Or for multiple cells:

  var range  = (Excel.Range) sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[3,3]);

Or for single cell:

  var range = (Excel.Range) sheet.Cells[1, 1];

You got it, they are all 1-based. To access a cell:

 var range = sheet.UsedRange;
 for (int i = 1; i <= range.Rows.Count; i++)
 {
    for(int j=1; j <= range.Columns.Count; j++)
    var s = (string) (range.Cells[i, j] as Excel.Range).Value2;
               // ProcessString(s);
 }

Clean up


Make sure to clean up after use. Here's how and don't forget to add try catch around it.


 book.Close(false, Type.Missing, Type.Missing);
 System.Runtime.InteropServices.Marshal.FinalReleaseComObject(book);
 System.Runtime.InteropServices.Marshal.FinalReleaseComObject(app);

Wednesday, March 16, 2016

Setup CocoaPods for Swift project

Cocoa Pods provides a standard way to manage dependent libraries. It only takes a few steps to set it up in a Swift project:
  • Assume you've already have a normal Xcode project
  • Open terminal window, $ cd to your project directory
  • Create a Podfile by runing $ pod init
  • Edit the Podfile to add any liberties you want to install within certain target
  • Make sure to uncomment use_frameworks if it's a Swift project
  • Run $ pod install
  • An xcworkspace project should be created, please use it to load your project moving forwards

Friday, March 11, 2016

Define Google Analytics Custom Dimension

Google Analytics' Custom Dimension feature provides a powerful way to combine custom data with  Analytics data. Here are a few steps to do it:

Create a GA account
  • Go to Admin UI, click ACCOUNT dropdown, select 'Create new account
  • Fill in account create form and click 'Get Tracking ID' 
Create environment specify property
  • Under PROPERTY section, select 'Create new property'
  • Fill in New Property form. You can use App Name for specific environment, like Staging, Dev etc.
  • Click 'Get Tracking ID' for specified environment
Sample code to track traffic:

<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-74922222-4', 'auto');
ga('send', 'pageview');
</script>


Create Custom Dimension
  • In Admin UI, click 'Custom Definitions' under PROPERTY section
  • Select 'Custom Dimensions', '+New Custom Dimension' button
  • Give a name and specify scope, check active and hit 'Create'
  • Follow the example codes to collect custom data
Sample code using javascript:

var dimensionValue = 'SOME_DIMENSION_VALUE';
ga('set', 'dimension1', dimensionValue);

View Result

  • In Report UI, select Audience>Custom>User Defined
  • From 'Secondary dimension' dropdown, select Custom Dimensions and your dimension name
  • You should be able to see traffics group by each value of your custom dimension.

Friday, March 4, 2016

Steps to upload iOS app to Apple Store


  • In XCode project General tab, make necessary updates to Version and Build number
  • Set Build Only Device to Generic iOS Device
  • Run Product>Archive
  • Upon successful build and archive, click 'Upload to App Store' button
  • Chose proper team for the submission
  • Click 'Upload' to send the app to Apple
  • Wait... until you get upload completed confirmation.
New build won't be available for TestFlight right away. To check status, login to iTunes Connect. Select your app>TestFight tab. Check iOS under TESTFLIGHT BUILDS section, click 'View All Builds' like, you may see your newly updated build is still in processing.

Tuesday, February 23, 2016

Git commands: get older version, set user email

From time to time there may be a need to play with a snapshot of an early version of code. Some Git/GitHub UI tool can help to do this, but it also just takes a few lines of command to do so. I use Mac as an example:

Check out older snapshot:
- Find the last commit you want to go back to. Copy the commit Id. It usually looks like this: 9d4f59ecf2eef3b8a46c5ba4a47a4efc27bf57b4
-  Open Terminal, change to the directory where you code base were checked out.
-  Enter: git checkout {Commit Id}
- You may see message like this:
You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by performing another checkout.

Return to latest version of master branch:
-  Enter: git checkout master

Setup user email for local Git repository:
- Enter: git config --global user.email "{user email}"

To verify user email:
- Enter: git config --global user.email