Amazon Mobile Analytics with Swift 3

Releasing your app into the wild doesn’t mean you have to say goodbye. Adding mobile analytics can provide a method for your furry binary creation to communicate back to you, relaying in fascinating detail all of its adventures in the wilderness.

Amazon Mobile Analytics offers an extremely versatile, cost effective (potentially free) tool for gathering user data and observing patterns. Along with customizable events AMA will track: daily active users, new users, usage sessions and in-app purchases. It’s especially nice if your app is cross platform as it also supports Android (number-of-times-device-has-exploded) and Fire OS.

At the time of writing this there doesn’t appear to be any official documentation for using Mobile Analytics in Swift 3. On top of that some of the infomation that is out there can be misleading. This is due to some changes in AWS and Swift. The great news is that once you’re on the right path it’s actually much easier to setup now!

Let’s go through the steps of adding AMA to your existing Swift 3 project:

Step 1 – Install CocoaPods

In order for your app to interact with AWS you’re going to need to install the SDK (software development kit) that they’ve made for iOS/Swift. A great way to manage these frameworks (namely the AWSMobileAnalytics and AWSCore) is with CocoaPods.

CocoaPods is a dependency manager which organizes a wide world of third party libraries. With a few short commands CocoaPods will fetch the latest version of the frameworks as well as setting up the Xcode workspace necessary to get started.

1)  Go into the Mac Terminal window

2) Enter:

sudo gem install cocoapods

3) Type in your password.

4) Enter:

pod setup --verbose

If all’s gone well CocoaPods is now installed. One issue that may come up is if you have an older version of Ruby installed. CocoaPods is built using Ruby, which comes with OSX. If the terminal can’t install CocoaPods because of this here’s how you update Ruby:

SDKS3_Ruby

So the command to run is:

rvm install 2.2
rvm use 2.2

If on the off chance you don’t have the RVM (Ruby Version Manager) run this command:

\curl -sSL https://get.rvm.io | bash

 

Step 2 – Use CocoaPods to Install the AWS SDK

1) Open the terminal and navigate to the directory you just made for the Xcode project. For example:

cd Documents/XcodeProjects/MyNewApp

2) Enter:

pod init

This creates the Podfile that we’ll use to configure our dependencies.

3) Enter:

open -a Xcode Podfile

This opens the Podfile in Xcode.

4) Edit the Podfile. The Podfile must be in this format and must include “use_frameworks!” – otherwise you’ll be in a WORLD OF PAIN  because the Xcode project wont link to the AWS framework. This will install the latest version of AWSCore and AWSMobileAnalytics.

# Podfile
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '10.0'
use_frameworks!

target 'MyNewApp' do
  pod 'AWSMobileAnalytics'

end

It’s very important that the platform you choose here matches the deployment target you have in Xcode under AppIcon > Gereral > Deployment Info > Deployment Target

5) Save + close Xcode

6) In the terminal enter:

pod install

So now if you look in the project folder you’ll see that not only are the frameworks installed but there’s also an Xcode workspace file. This workspace file includes the project file as well as the AWS frameworks. From now on it’s very important that you work using the workspace file (not the project file).

Step 3 – Skip Step 3 and Rejoice!

Previous the SDK required creating an Objective-C bridging header. (Even some of the current AWS documentation suggests this). To my understand the SDK in Swift no longer requires it.

Congratulations – you just saved some time. Skip, SKIP merrily around the office!

Step 4 – Setup Mobile Analytics in the AWS Console

1) Go to your AWS console. Hunt down the Mobile Analytics icon.

2) Add a new app

3) Give the app a name and hit “Create app”

4) You’ll see a tab that says: “Select an Amazon Cognito Identity Pool to associate with your app.”

Here’s where things have changed a bit. Previously to use AMA you had a setup up a dedicated Cognito Identity Pool. This would give the app it’s own ARN (Amazon Resource Name). However at this time if you’re just going to add Mobile Analytics you can select the “Mobile_Analytics_Shared_Pool”. This will provide your app with the necessary credentials + policies to access AMA. Your specific app is then identified by AMA using the “Amazon Mobile Analytics App ID”.

5) At the time of this post the implementation code at the bottom of the page is still written in Objective-C. No worries. Just copy and paste it to a text file so you can reference the AMA app ID and the Cognito Identity Pool ID. If you ever need to see these again go to Mobile Analytics > App Name: (Tab) > Manage Apps > View Integration Steps.

If you’re interested; in Identity and Access Management (IAM), go to Roles. Here you can see that the shared mobile analytics role only has these permissions:

ama_iampolicy

Step 5 – Skip Step 5!

It was previously necessary to update the info.plist file. However, it appears this is no longer needed. I’ll leave the info here just for reference.

amainfoplistedit

Step 6 – Setup the AppDelegate

We’re getting close! Now we get to write some Swift – yey!

1) Navigate to the AppDelegate Swift file. Add “import AWSMobileAnalytics”.

You may find that Xcode gives you an error saying “no such module…”. To fix this go to Menu > Product > Clean . Then Menu > Product > Run . + you should be good to go.

2) Add the following inside didFinishLaunchingWithOptions. Switch out the values of the ids for your own.

        // provides "verbose" level of log information
        AWSLogger.default().logLevel = AWSLogLevel.verbose
        
        let credentialsProvider = AWSCognitoCredentialsProvider(
            regionType: AWSRegionType.usEast1,
            identityPoolId: "YOUR_IDENTITY_POOL")
        
        let configuration = AWSServiceConfiguration(
            region: AWSRegionType.usEast1,
            credentialsProvider: credentialsProvider)
        
        AWSServiceManager.default().defaultServiceConfiguration = configuration
        
        let analyticsConf = AWSMobileAnalyticsConfiguration.init()
        
        // configure analytics with the service manager's configuration
        analyticsConf.serviceConfiguration = AWSServiceManager.default().defaultServiceConfiguration
        
        // initialize mobile analytics
        _ = AWSMobileAnalytics.init(forAppId: "YOUR_APP_ID", configuration: analyticsConf)
        
        return true

At the time of writing this there’s no official AWS AMA Swift 3 documentation. If you see any room for improvement (or if things change) please let me know in the comments. Thx.

Step 7 – Add Custom Events

Custom events can be added anywhere in your code. Some places you might record events:

  • the viewDidAppear in a vc to see how often users visit that screen
  • when a user creates a new Core Data entity
  • when a user completes a level in a videogame

AMA events can also include Attributes and record more specific Metrics as demonstrated in this example. You’ll need to include “import AWSMobileAnalytics” in any Swift file using this code.

        // example of event within a videogame
        
        let eventClient = AWSMobileAnalytics(forAppId: "YOUR_APP_ID").eventClient
        
        guard let client = eventClient else {
            print("Error creating AMA event client")
            return
        }
        
        guard let event = client.createEvent(withEventType: "Achievement") else {
            print("Error creating AMA event")
            return
        }
        
        event.addAttribute("Completed", forKey: "Level7")
        event.addMetric(590, forKey: "Level7Score")
        client.record(event)

Event and usage data is transmitted over the network when the user places the app in the background.

 

Step 8 – Behold the Magic

At this point you should be ready to rock. When you debug the app on your device or simulator you should see a “verbose” amount of code in the console. This is generated by our AWSLogger and can be extremely useful because events can take some time to show up in the AWS console. How much time? Somewhere between a few minutes and an hour. In your Xcode console you’ll want to look out for the line that says “Successful submission of x events”

ama_success

In the AWS AMA console you should be able to see your custom event:

ama_consoleevent

Cost?

Like most services in AWS, Mobile Analytics is free when your app is small, then incrementally increases if/when your app blows up. Currently you get 100 miiiiiiillion events per month free. Then it’s $1 per million per month extra.

Conclusion

Hopefully you’ve got through that unscathed! Once it’s up and run Mobile Analytics can be a great tool to put in you app. Not only giving you feedback that could improve the user experience but also hopefully giving you the knowledge that people across the world are getting value from your creation!

If you’ve found the post helpful please share with the links below!

Read more on the official AWS documentation page here

For the latest updates + blog posts follow me on twitter here.

 

 

Leave a Reply