August 30th, 2018 • By Jason Skowronski
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.
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.
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.
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
-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.#import <Rollbar/Rollbar.h>
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
}
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:
/usr/bin/python
."""
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'):
exit(0)
ACCESS_TOKEN = 'POST_SERVER_ITEM_ACCESS_TOKEN'
dsym_file_path = os.path.join(os.environ['DWARF_DSYM_FOLDER_PATH'],
os.environ['DWARF_DSYM_FILE_NAME'])
zip_location = '%s.zip' % (dsym_file_path)
os.chdir(os.environ['DWARF_DSYM_FOLDER_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']):
zipf.write(root)
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),
shell=True)
p.communicate()
Note: Make sure you replace POST_SERVER_ITEM_ACCESS_TOKEN
with a server scope access token from your project in Rollbar.
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() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
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."
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.
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.