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. By Andy Pereira.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 2 of 3 of this article. Click here to view the first page.

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.