Over a million developers have joined DZone.

Error Monitoring in iOS

DZone's Guide to

Error Monitoring in iOS

We'll look at how to handle errors in iOS apps using Swift, Python, and a popular error monitoring service. Read on to get started!

· Web Dev Zone ·
Free Resource

Bugsnag monitors application stability, so you can make data-driven decisions on whether you should be building new features, or fixing bugs. Learn more.

In mobile apps, it’s important to monitor errors so you can understand your user’s experience. Your team should know quickly when there are problems with the app itself or your backend services so you can fix the issue before more customers are affected. We’ll show you how to handle errors in iOS apps. We’ll then show you how Rollbar error monitoring can give you better visibility into errors and help you troubleshoot them faster.

Native Error Handling in iOS

There are multiple ways to implement exception handling in Objective-C and Swift. We’ll focus on Swift in our examples as its a newer language. You’ll commonly use NSError to create runtime errors and use do-catch statements to handle them:

do {
  throw NSError(domain: "my error description", code: 42, userInfo: ["ui1":12, "ui2":"val2"] )
} catch let error as NSError {
  // handle the error
  print("Caught NSError: \(error.localizedDescription), \(error.domain), \(error.code)")

Swift also offers a mechanism to handle uncaught exceptions. This allows you to track the error, display a message to the user, or attempt to recover. See the example below.

NSSetUncaughtExceptionHandler { exception in
  // handle the error
  print("Uncaught exception", exception)

This lets you easily track the error in logs during development. However, it doesn’t offer an easy way to track errors once the app is installed on your customer’s phone.

Error Monitoring With Rollbar

Rollbar offers an easy way to track exceptions and errors in your apps. It automatically captures errors that occur anywhere in the app, and reports on them in real-time. It automatically groups errors for quick summaries, offers full stack monitoring on the web and server side, and person tracking so you can prioritize errors that affect the most people. These benefits help developers quickly identify and fix errors.

Below, you can see that we’ve created an example app that triggers an exception when the user clicks on a button. Rollbar tracks the error message and includes a stack trace where you can see the line of code that caused the error. It also offers a wealth of other contextual information to help you prioritize errors and find the root cause faster.

Screenshot of Rollbar iOS Error

How to Set up an iOS Project on Rollbar

  1. Visit https://rollbar.com and sign up for an account if you haven’t done so yet. Next, create your project and select Other from the list of notifiers. Select the client-side access token that is generated for you. You’ll need this to configure Rollbar in the steps below.
  2. To install iOS SDK in your project, use the following approaches. You can read more in the Rollbar iOS documentation.

With Cocoapods

In your pod file add the Rollbar iOS SDK and run the pod install. You can find pod under pods directory in your project.

pod "Rollbar", "~> 1.0.0"

Make sure to declare your platform as iOS at the top of your Podfile:

platform :ios, '7.0'

Without Cocoapods

  1. Download the Rollbar framework. Note that depending on the version of Xcode you use to build your app, you might have to download a different version of the framework if you have bitcode enabled. This is because of the way it handles bitcode serialization. The latest release on the releases page should have a zip file for the most recent versions of Xcode.
  2. Extract the Rollbar directory in the zip file to your Xcode project directory.
  3. In Xcode, select File -> Add Files to "[your project name]" and choose the Rollbar directory from step 2. Note: If step 3 doesn’t work you can also extract the Rollbar directory anywhere and drag the .framework files into Xcode, allowing Xcode to correctly configure the Frameworks.
  4. Add the libc++ library to your link binary in the libraries build phase.
  5. Ensure that -ObjC is in your "Other Linker Flags" setting. Note that the -all_load flag is not recommended but would also work for this purpose if you already have that set.

Adding Rollbar in your code

  1. Add Rollbar in the Bridging Header file. If you have no Bridging Header file, the easiest way to correctly configure it is to add an empty objective-c (dummy.m for instance) file. When you do so, Xcode will prompt you to create a bridging header file and will configure your build environment to automatically include those headers in all your Swift files. After creating the Bridging-Header file, you can delete the objective-c file.
#import <Rollbar/Rollbar.h>
  1. Configure Rollbar in the AppDelegate class. You can find AppDelegate under the model directory in the project.
func application(_ application: UIApplication, didFinishLaunchingWithOptions   launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
  let config: RollbarConfiguration = RollbarConfiguration()
  config.environment = "production"
  Rollbar.initWithAccessToken("ACCESS-TOKEN", configuration: config)
  return true

Upload Debugging Symbols to Rollbar

Finally, you need upload the dSYM file to the Rollbar so it can show you the source code that generated the error. To automatically send dSYM files to Rollbar whenever your app is built in release mode, add a new build phase to your target in Xcode:

  1. Click on your project, then select "Build Phases."
  2. In the top menu bar, click "Editor," then “Add Build Phase,” then “Add Run Script Build Phase.”
  3. Change the "Shell" to /usr/bin/python.
  4. Paste the contents of the below upload_dysm.py script into the box, using "Paste and Preserve Formatting" (Edit -> Paste and Preserve Formatting).
Python script that zips and uploads a dSYM file package to Rollbar
during an iOS app's build process.

For instructions on setting up this script for your app in Xcode, see
the README at https://github.com/rollbar/rollbar-ios/blob/master/README.md.

import os
import subprocess
import zipfile

if (os.environ['DEBUG_INFORMATION_FORMAT'] != 'dwarf-with-dsym' or
        os.environ['EFFECTIVE_PLATFORM_NAME'] == '-iphonesimulator'):


dsym_file_path = os.path.join(os.environ['DWARF_DSYM_FOLDER_PATH'],
zip_location = '%s.zip' % (dsym_file_path)

with zipfile.ZipFile(zip_location, 'w', zipfile.ZIP_DEFLATED) as zipf:
    for root, dirs, files in os.walk(os.environ['DWARF_DSYM_FILE_NAME']):

        for f in files:
            zipf.write(os.path.join(root, f))

# You may need to change the following path to match your application
# settings and Xcode version
plist_command = '/usr/libexec/PlistBuddy -c "Print :CFBundleVersion" "%s"'
p = subprocess.Popen(plist_command % os.environ['PRODUCT_SETTINGS_PATH'],
                     stdout=subprocess.PIPE, shell=True)
stdout, stderr = p.communicate()
version = stdout.strip()

curl_command = ('curl -X POST "https://api.rollbar.com/api/1/dsym" '
                '-F access_token=%s -F version=%s -F bundle_identifier="%s" '
                '-F dsym=@"%s"')
p = subprocess.Popen(curl_command % (ACCESS_TOKEN, version,
                     os.environ['PRODUCT_BUNDLE_IDENTIFIER'], zip_location),

Note: Make sure you replace POST_SERVER_ITEM_ACCESS_TOKEN with a server scope access token from your project in Rollbar.

Test Rollbar With an Example iOS App

To test that it’s working, create a controller that will generate an error message. In the example below, you’ll be able to generate an error by clicking the "Generate an error" button. Download our open source example on GitHub to try it yourself.

import UIKit
import Rollbar

class ViewController: UIViewController {
  var test: String!  // Nil variable declare.
  // Generate an error button which will show in the UI. While clicking on, this method will call and generate nil reference error.

  @IBAction func clickButton(_ sender: Any) {
    test.append("ab")  // Generating Nil reference exception due to null reference

  override func viewDidLoad() {

  override func didReceiveMemoryWarning() {


Viewing Errors in Rollbar

Open Rollbar to see what these errors look like in your account’s item page. The error you just generated should be titled "Application terminated."

Image title

Get more details by clicking on the item. You can now see a traceback showing the exact source code file, method, and line number that generated the error. In this case, the error was generated in ViewController.swift on line 13.

Image title

It’s pretty easy to get error tracking across your entire app thanks to Rollbar’s iOS SDK. It takes only a few minutes to set up, and you will have way more context to track and debug problems faster in the future. You’ll know about errors right away so your users can experience your app the way it was meant to be. Learn more about Rollbar’s features for iOS.

If you haven’t already, sign up for a 14-day free trial of Rollbar and let us help you take control of iOS errors.

Monitor application stability with Bugsnag to decide if your engineering team should be building new features on your roadmap or fixing bugs to stabilize your application.Try it free.

data errors ,error monitoring ,web dev ,ios ,app development

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}