AWS Pinpoint Tutorial for iOS: Getting Started

In this AWS Pinpoint tutorial, you’ll learn how to integrate Pinpoint SDK in iOS for app analytics. You’ll also learn to add, upload, and analyze events.

Version

  • Swift 4, iOS 11, Xcode 9

Most developers will agree that mobile app analytics information can be invaluable. Knowing how long a user stays on a screen, which UI/UX experiments work best, or what users like to spend money on can help you make more informed decisions to improve your apps. If you’re not using an analytics tool or find your current tool lacking, you should consider introducing analytics into your development practices as soon as possible.

Amazon’s previously separate AWS mobile analytics tool has since been rolled into Amazon Pinpoint. This tutorial will help you get started with AWS Pinpoint app analytics for iOS.

If you’re curious about the general ins and outs of mobile analytics, you can read through the precursor to this tutorial here to get caught up: Getting Started with Mobile Analytics

You’ll need to have an AWS account for this tutorial. If you don’t have one yet, you can get started with an AWS account here; simply look for the Create A Free Account link.

AWS Pinpoint Tutorial

You will also need a credit card to set up your account as a safeguard. You will not get charged as long as you are within the free daily allotment of 100,000,000 analytics events.

Getting Started

Use the Download Materials button at the top or bottom of this tutorial to download the starter project.

This project builds upon the Beer Tracker app from a previous tutorial. The app lets users keep track of and rate their favorite beers. For this tutorial, you’ll add analytics to understand what users are actually doing when they are using your app.

Setting Up the AWS Account

Your first task is to cloud-enable your app so it can interact with AWS services. Once you have an active AWS account, head to the AWS Console.

Click on the Services dropdown. Then click on the Mobile Hub service. You’ll arrive at the following page:

Follow the steps below to cloud-enable your Beer Tracker app with AWS Mobile Hub service:

  1. Click Create. Set Your Project Name to Beer Tracker. Tick the Allow AWS Mobile Hub to administer resources on my behalf box. Click Next.
  2. Select iOS as the platform and then click Add. This will add AWS cloud services to your app.
  3. Click Download Cloud Config. You’ll use this cloud configuration file in your Xcode project. Then click Next.
  4. The starter project has integrated the AWS Mobile SDK for you. Simply click Done.

Once you have cloud-enabled your app, you should now see a screen that looks like this:

Integrating Pinpoint in Xcode

Open the starter project by selecting BeerTracker.xcworkspace. The app uses CocoaPods and has integrated the Pinpoint SDK into your project. Build and run the app, and take a look around.

Note: If you have any build issues, you may need to reinstall the pods. Navigate to your project’s directory in Terminal, and run pod install. You can learn more about getting started with CocoaPods here.

The Beer Tracker app allows users to record the following details about the beer they consume:

  • Name
  • Rating
  • Photo
  • Any notes about it

While this seems fairly straightforward, it may be unclear to you how much users actually interact with each of these features. Is it worthwhile to keep investing in your current UI? Would it make sense to give your app a new look and feel? Adding analytics may help you answer these questions, and more.

First, you’ll need to add the awsconfiguration.json file you downloaded earlier to the project. Drag the file to the Supporting Files group. Ensure that Copy items if needed and Add to targets are both selected. Click Finish. You should be able to see the file in the Supporting Files group:

This file contains all the information needed for the Pinpoint SDK to properly set up its connection to AWS. Open awsconfiguration.json and you’ll see information about the region, the Cognito PoolId, and the AppId used for your app.

Open AnalyticsManager.swift and you’ll see some existing code. Add the following method to AnalyticsManager:

func setupClient(withLaunchOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) {
  pinpoint = AWSPinpoint(configuration:
    AWSPinpointConfiguration.defaultPinpointConfiguration(launchOptions: launchOptions))
}

Simply, this code sets up the pinpoint property to be used throughout the app.

Next, open AppDelegate.swift, and add the following right after the existing import:

import AWSPinpoint

Now replace application(_:didFinishLaunchingWithOptions:) with the following:

func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
  // 1
  AWSDDLog.sharedInstance.logLevel = .verbose
  // 2
  AWSDDLog.add(AWSDDTTYLogger.sharedInstance)
  // 3
  AnalyticsManager.shared.setupClient(withLaunchOptions: launchOptions)
  return true
}

Here’s what you’ve added:

  1. You turned on the logging feature of the AWS SDK platform. By setting the log level to .verbose, you’ll see every log statement that is produced by Pinpoint or any other AWS services available.
  2. You set the AWSDDLog to print to your Xcode console. You’ll see this in action soon.
  3. You set up the AnalyticsManager using the code you added previously.

Build and run the app, open the debug area, and you should see the following in the console:

With that, you’re all set up to use the Pinpoint SDK.

Pinpoint Analytics Events

Pinpoint can track several different types of analytics events to help you understand what’s going on in your app:

  • Custom events
  • Monetization events
  • Authentication events
  • Session events

You’ll focus only on the first two types — Custom and Monetization events — in this tutorial. However, if you look into the documentation of the other two events, you’ll see that they aren’t too different from the ones covered here.

Adding Custom Events

The first thing you’ll track is the number of people adding a beer record in your app. To do this, you’ll need to create a custom event.

First, open AnalyticsManager.swift, and add the following method to AnalyticsManager:

func create(event: String) {
  guard let pinpoint = pinpoint else { return }
  // 1
  let event = pinpoint.analyticsClient.createEvent(withEventType: event)
  // 2
  pinpoint.analyticsClient.record(event)
}

Here’s what you’ve added:

  1. You’ve created an event with the provided event type. This is all you need to do to create a custom event.
  2. Here, you’ve recorded the event. Take notice that you haven’t actually uploaded the event to Pinpoint, just saved it for later. Pinpoint will save these events, even if the app is closed, to be uploaded later.

Open BeerDetailViewController.swift, and add the following to the end of viewDidLoad():

AnalyticsManager.shared.create(event: Event.visitedBeerDetailViewController)

Here, you call create(event:) with the Visited BeerDetailViewController event type.

Build and run. Before you navigate anywhere in the app, clear the console by clicking on the Trash icon in the lower right of the console. In the app, tap on the + button in the upper-right corner. Check the console, and you’ll see that a saveEvent log is added along with its event type.

Uploading and Analyzing Events

This data doesn’t do a lot of good just sitting on the user’s device. You need a way to time and upload that information to Pinpoint. You could upload each and every event when it occurs, but this would cause performance issues along with unnecessary network overhead. Events aren’t only stored in memory but are serialized and saved for future use as well. This means you can upload the events in batches.

Open AnalyticsManager.swift, and add the following method to AnalyticsManager:

func uploadEvents() {
  guard let pinpoint = pinpoint else { return }
  pinpoint.analyticsClient.submitEvents()
}

By calling submitEvents(), you’ve done all that’s required to submit any events awaiting upload.

Now, open BeerDetailViewController.swift. At the end of viewWillDisappear(_:), add the following:

AnalyticsManager.shared.uploadEvents()

Build and run. Be sure to clear the console before doing anything in the app. Once cleared, create a new beer, and go back to the main list. In the console, you should see something like the following:

If you go through the debug log, you’ll start to notice a lot of familiar-looking information. You’ll see your event name, and a lot of other available data. The last two lines in the console are important.

Assuming you have a working internet connection, the last line tells you the number of uploaded events, along with a response code of 202, which simply means Accepted. Since AWS requires some time to process the data that is sent, the 202 response lets you know that the data was properly received.

To see the uploaded events, head to the Pinpoint console. Open your app and select Analytics/Events. If you don’t see anything, don’t worry; AWS can take a few minutes to process the received data. Refresh every minute or so, until you see your processed data:

Select the Event dropdown, and you’ll see an option for Visited BeerDetailViewController. This is a custom event type that you’re tracking right now, but you’ll want to add more custom events in order to better understand your user’s behavior.

Adding More Custom Events

In BeerDetailViewController.swift, add the following to saveBeer(), right after the guard statement:

if detailBeer.name != name {
  AnalyticsManager.shared.create(event: Event.editedName)
}
if detailBeer.rating != ratingView.rating {
  AnalyticsManager.shared.create(event: Event.editedRating)
}
if detailBeer.note != notesView.text {
  AnalyticsManager.shared.create(event: Event.editedNotes)
}

In imagePickerController(_:didFinishPickingMediaWithInfo:), add the following at the end of the method:

AnalyticsManager.shared.create(event: Event.editedImage)

Here you’ve added events to be recorded in case the user changes any info on the beer object. With this information, you might be able to figure out what users find most valuable, or how often they make mistakes while using your app.

Adding Monetization Events

Another great feature of Pinpoint is the ability to look at a simple dashboard and see the amount of money your app is bringing in. Whether it’s through Apple’s in-app purchases or your own e-commerce platform, Pinpoint can take care of reporting the numbers for you.

On the initial screen of the app, you should see a Send Tip button in the top left corner of the screen. This is the app’s pseudo “in-app purchase” button.

Pressing the button only results in printing a log that says “Fake in-app purchase”. To begin logging your revenue, open AnalyticsManager.swift and add the following method:

func createMonetizationEvent(productId: String, price: Double, currency: String, quantity: Int) {
  guard let pinpoint = pinpoint else { return }
  let event = pinpoint.analyticsClient.createVirtualMonetizationEvent(withProductId: productId,
                                                                      withItemPrice: price,
                                                                      withQuantity: quantity,
                                                                      withCurrency: currency)
  pinpoint.analyticsClient.record(event)
  uploadEvents()
}

Here you’ve created a Virtual Monetization Event. The event takes in the following information:

  • Product ID: The unique identifier for your individual product.
  • Price: The price the user paid.
  • Quantity: The number of items purchased.
  • Currency: The currency that the user paid with.

Now open BeersTableViewController.swift, and replace sendTip(_:) with the following:

@IBAction func sendTip(_ sender: Any) {
  // Mock In-App Purchase
  AnalyticsManager.shared.createMonetizationEvent(productId: "Send Tip",
                                                  price: 0.99,
                                                  currency: "US",
                                                  quantity: 1)
}

This method creates a virtual purchase event with hardcoded values.

Build and run. Tap the Send Tip button a few times.

Navigate to your Pinpoint analytics dashboard, and head to Revenue tab. Remember, it can take a few minutes to see the results. When everything is processed, you should be able to see new revenue data like below:

For reference, Amazon does provide an easy method to track actual in-app purchases. Here is an example of a method that you can implement inside of AnalyticsManager.swift that would do just that:

func createInAppPurchaseEvent(transaction: SKPaymentTransaction, product: SKProduct) {
  guard let pinpoint = pinpoint else { return }
  let event = pinpoint.analyticsClient.createAppleMonetizationEvent(with: transaction, with: product)
  pinpoint.analyticsClient.record(event)
  uploadEvents()
}

Instead of having to provide all of the individual values, the SDK takes care of pulling out the proper in-app purchase data for you.

Adding Attributes and Metrics to Events

At times, you’ll probably want to provide more data for a custom event than just its name. Luckily with the Pinpoint SDK, you can add attributes and metrics onto an Event object.

Open AnalyticsManager.swift, delete create(event:), and add the following method:

func create(event: String, attributes: [String: String]? = nil, metrics: [String: NSNumber]? = nil) {
  guard let pinpoint = pinpoint else { return }
  
  let event = pinpoint.analyticsClient.createEvent(withEventType: event)
  
  // 1
  if let eventAttributes = attributes {
    for (key, attributeValue) in eventAttributes {
      event.addAttribute(attributeValue, forKey: key)
    }
  }
  
  // 2
  if let eventMetrics = metrics {
    for (key, metricValue) in eventMetrics {
      event.addMetric(metricValue, forKey: key)
    }
  }
  pinpoint.analyticsClient.record(event)
}

This new method does nearly the same thing as create(event:), but also adds the attributes and metrics. When creating events, it’s best to think of them as generic actions performed by a user. Attributes and metrics are the data that fine-tune the information about a specific event:

  1. Attributes: These are string values that can represent things such as titles of buttons pressed, or values entered into text fields.
  2. Metrics: These are number values that can represent things such as time taken to complete a task, the number of times a button was pressed, or any other quantitative value associated with your event.

When deciding on which events to track in your app, you’ll want to come up with a game plan. It’s not a good idea to create dynamic event names that contain information that would be better represented as an attribute or a metric. For example, if you want to know how long a user is spending on a particular screen, you wouldn’t want to add the time to the event title, like this:

DetailViewController Time Spent: 1 minute 27 seconds

If you did this, you’d find hundreds or even thousands of events in Pinpoint. The data would be next to impossible to sift through.

To see attributes and metrics in action, open BeerDetailViewController.swift, and add the following property:

var startTime: Date?

Next, in viewDidLoad(), add the following just after the call to super.viewDidLoad():

startTime = Date()

Here you have a property that is tracking the moment the screen is loaded. You’ll use this as a way to see how long the user is on the screen.

Next, replace viewWillDisappear(_:) with the following:

override func viewWillDisappear(_ animated: Bool) {
  super.viewWillDisappear(animated)
  if let startTime = startTime {
    // 1
    let endTime = Date()
    // 2
    let interval = NSNumber(value: endTime.timeIntervalSince(startTime))
    // 3
    AnalyticsManager.shared.create(event: Event.timeSpent, metrics: ["timeSpent": interval])
  }
  AnalyticsManager.shared.uploadEvents()
  saveBeer()
}

Here’s a breakdown of what you’ve added:

  1. Create an end date to compare against the start date.
  2. Gathere the time interval between the two dates.
  3. Create a new event, with a metrics dictionary, that contains the time interval.

Next, in saveBeer(), modify the following event creation:

AnalyticsManager.shared.create(event: Event.editedName)

…to this:

AnalyticsManager.shared.create(event: Event.editedName,
                               attributes: ["New Beer Name": name, "Old Beer Name": detailBeer.name])

Build and run, create a few beer records, and go back to edit their names.

Now you’ll be able to see what has changed once the users edit the names of their drinks. While it may not necessarily tell you “why”, it does provide you an insight into “what” is happening in your app. For example, did you leave Correction on for your text field? If so, and the user didn’t catch it, maybe the app improperly corrected the name of a foreign beer and the user had to spend time fixing it. In a situation like this, you’d have to analyze the data yourself to determine that.

Unfortunately, this data isn’t as easily accessible as plain event names. This is where Pinpoint’s simplicity ends. There are two ways you can view this information within AWS. The first is to set up a Kinesis Stream and roll out your own application. While this sounds fun, this would require more knowledge of the AWS platform than is available in this tutorial.

The second option is to view the Mobile Analytics console still available in AWS, which makes things quite easy.

Navigate back to your AWS console. Search for and click on Mobile Analytics under the Services dropdown. Once there, navigate to the Custom Events tab. You can then select Time Spent Editing Beer under Custom Event Name. Under Attributes and Metrics, select Metrics/timeSpent. You should now see a chart similar to the one below:

While you cannot see all the information found in Pinpoint, and there is some overlap of data, you can see all the information related to your custom events here.

Where to Go From Here?

You can download the completed version of the project using the Download Materials button at the top or bottom of this tutorial.

In this tutorial, you learned how to:

  • Set up an AWS account
  • Cloud enable an iOS App for AWS Mobile Hub
  • Integrate the Pinpoint SDK in Xcode
  • Send custom events
  • Send monetization events
  • View uploaded events within Pinpoint and AWS Mobile Analytics

If you have more questions about Pinpoint, you can read the Pinpoint documentation here.

If you have any questions or comments, please join in the forum discussion below!

Contributors

Comments