iOS integration guide

Add Bugsnag to your iOS & iPadOS projects for automatic iOS crash reporting — automatically capture and report crashes in released applications.

New to Bugsnag? Create an account

Installation

This documentation is for version 6 of the Bugsnag iOS notifier. If you are using older versions, we recommend upgrading to the latest release using our Upgrade guide. Documentation for the previous release can be found on our legacy pages.

Using CocoaPods

Add the Bugsnag pod to your Podfile:

pod 'Bugsnag'

Don’t forget to run pod install after updating your Podfile.

Using Swift Package Manager

In your Xcode project: File → Swift Packages → Add Package Dependency…

Use https://github.com/bugsnag/bugsnag-cocoa as the package repository URL.

Using Carthage

Add Bugsnag to your Cartfile:

github "bugsnag/bugsnag-cocoa"

Then run carthage update --platform ios to generate the frameworks to add to your project from Carthage/Build.

Manual installation

  1. Clone the Bugsnag GitHub repository and its submodules into your source control environment:

    git clone --recursive https://github.com/bugsnag/bugsnag-cocoa
    cd bugsnag-cocoa && git checkout tags/<latest release>
    

    where <latest release> is the most recent release of the library

  2. Open Xcode and drag Bugsnag.xcodeproj to your workspace.

  3. Select your project in the Project Navigator, then add the following libraries to Frameworks, Libraries and Embedded Content section of your app’s target:

    • Bugsnag.framework (select iOS, tvOS or macOS as appropriate)
    • SystemConfiguration.framework
    • libc++.tbd
    • libz.tbd

Basic configuration

Configure your API key by adding a bugsnag Dictionary to your Info.plist file:

Set the apiKey in your Info.plist

Or in XML:

<key>bugsnag</key>
<dict>
    <key>apiKey</key>
    <string>YOUR-API-KEY</string>
</dict>

You can find your API key in Project Settings.

App Delegate

If your app implements an app delegate, import the Bugsnag module and initialize Bugsnag in the application:didFinishLaunchingWithOptions: method:

#import <Bugsnag/Bugsnag.h>

@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
        didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [Bugsnag start];
    return YES;
}
import Bugsnag

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication,
            didFinishLaunchingWithOptions launchOptions: 
            [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        Bugsnag.start()
        return true
    }
}

SwiftUI App Life Cycle

If your app adopts the SwiftUI App Life Cycle and does not implement an app delegate, import the Bugsnag module and initialize Bugsnag within the App conformer’s initializer:

import Bugsnag

@main
struct SwiftUIApp: App {
    init() {
        Bugsnag.start()
    }
}

App extensions

Within application extensions, initialize Bugsnag within the extension view controller initializers:

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    [Bugsnag start];

    return self;
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil
                         bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    [Bugsnag start];

    return self;
}
required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    Bugsnag.start()
}

required override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
    super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    Bugsnag.start()
}

Note: You will need to add the Bugsnag library to each application extension target you wish to use Bugsnag in

An application extension creates a new target in your Xcode project. Bugsnag needs to be added to each target that you want to have access to the bugsnag-cocoa library.

Using Swift Package Manager

  1. First, install Bugsnag into your main application as described in the Swift Package Manager installation guide.
  2. From your Project navigator, select your root project. Then, select the target to which you want to add Bugsnag. Go to the “General” tab.
  3. Under “Frameworks and Libraries”, click the “+” button, select “Bugsnag” from under “Bugsnag Package”, click “Add”.

Using CocoaPods

  1. First, install Bugsnag into your main application as described in the CocoaPods installation guide
  2. In your Podfile, add Bugsnag to your new application extension target. Note, you may need to add a new target to your Podfile if this does not already exist. For example:
target 'MyMainApp' do
  pod 'Bugsnag'
end

+ target 'MyApplicationExtension' do
+   pod 'Bugsnag'
+ end

Using Carthage

  1. First, install Bugsnag into your main application as described in the Carthage installation guide.
  2. From your Project navigator, select your root project. Then, select the target to which you want to add Bugsnag, go the “General” tab.
  3. Drag & drop the Bugsnag.framework that you built using Carthage previously from Finder into the “Frameworks and Libraries” of this target.

Configuring symbolication

Stacktraces from Apple platforms include backtraces with memory addresses, but symbolication is required to replace the memory addresses with human-readable function names, file paths, and line numbers. Follow the symbolication guide to configure symbolication during your build and release process.

Further configuration

If you’d like to configure Bugsnag further, check out the configuration options reference.

Reporting unhandled exceptions

After completing installation and basic configuration, unhandled exceptions, assertion failures and signal terminations will be reported and automatically appear on your Bugsnag dashboard.

Unhandled exceptions are sent to your Bugsnag dashboard when the app next launches. They will not be reported when the debugger is attached.

Reporting out-of-memory terminations

Bugsnag detects terminations of your app caused by the operating system due to high memory usage.

Out of Memory (OOM) detection is enabled by default as part of the basic configuration steps. If you wish to disable it, see the enabledErrorTypes configuration option.

OOMs are sent to your Bugsnag dashboard when the app next launches. They will not be reported when the debugger is attached.

Reporting app hangs

Bugsnag detects app hangs (when the main thread is unresponsive for a period of time), alerting you of issues with your app’s responsiveness.

Fatal app hangs are sent to your Bugsnag dashboard when the app next launches.

Follow the Reporting app hangs guide to configure this functionality.

Reporting handled exceptions

If you would like to send handled exceptions to Bugsnag, you can pass any NSError object to Bugsnag’s notifyError method:

NSError *error = nil;
BOOL success = [[NSFileManager defaultManager] removeItemAtPath:@"//invalid/file" error:&error];
if (!success) {
    [Bugsnag notifyError:error];
}
do {
    try FileManager.default.removeItem(atPath:"//invalid/file")
} catch {
    Bugsnag.notifyError(error);
}

Instances of NSException can be sent using the notify method:

@try {
    [NSJSONSerialization dataWithJSONObject:badlyFormattedJson options:0 error:nil];
} @catch (NSException* exception) {
    [Bugsnag notify:exception];
}
let exception = NSException(name:NSExceptionName(rawValue: "NamedException"),
                            reason:"Something happened",
                            userInfo:nil)
Bugsnag.notify(exception)

Adding diagnostics or adjusting severity

It can often be helpful to adjust the severity or attach custom diagnostics to handled exceptions. For more information, see Reporting handled errors.

Sending diagnostic data

Automatically captured diagnostics

Bugsnag will automatically capture and attach the following diagnostic data to every exception report:

  • Full stack traces for all threads.
  • App state including running time and time in foreground.
  • Build information including name, version/build and release stage.
  • Device specification including model, OS version and total memory.
  • System state including orientation, free memory, available disk space and battery level.

For more information see Automatically captured data.

Attaching custom diagnostics

It can often be helpful to attach application-specific diagnostic data to error reports. This can be accomplished by setting a callback which will be invoked before any reports are sent to Bugsnag:

BugsnagConfiguration *config = [BugsnagConfiguration loadConfig];
[config addOnSendErrorBlock:^BOOL (BugsnagEvent *event) {
    [event addMetadata:@"Acme Co." withKey:@"name" toSection:@"account"];
    [event addMetadata:@(YES) withKey:@"paying_customer" toSection:@"account"];

    // Return `NO` if you'd like to stop this error being reported
    return YES;
}];
[Bugsnag startWithConfiguration:config];
let config = BugsnagConfiguration.loadConfig()
config.addOnSendError { (event) -> Bool in
    event.addMetadata("Acme Co.", key:"name", section:"account")
    event.addMetadata(true, key:"paying_customer", section:"account")

    // Return `false` if you'd like to stop this error being reported
    return true
}
Bugsnag.start(with: config)

For more information, see Customizing error reports.

Identifying users

In order to correlate errors with customer reports, or to see a list of users who experienced each error, it is helpful to capture and display user information. Bugsnag includes helpers attaching an identifier, email address, and name to reports that will be searchable in the dashboard:

[Bugsnag setUser:@"3" withEmail:@"bugs.nag@bugsnag.com" andName:@"Bugs Nag"];
Bugsnag.setUser("3", withEmail: "bugs.nag@bugsnag.com", andName: "Bugs Nag")

For more information, see Adding user data.

Logging breadcrumbs

In order to understand what happened in your application before each crash, it can be helpful to leave short log statements that we call breadcrumbs. A configurable number of breadcrumbs are attached to each error report to help diagnose what events led to the error.

Automatically captured breadcrumbs

By default, Bugsnag captures common events including:

  • Low memory warnings
  • Device rotation
  • Menu presentation
  • Screenshot capture (not the screenshot itself)
  • Undo and redo
  • Table view selection
  • Window visibility changes
  • Non-fatal errors

Leaving custom breadcrumbs

You can use the leaveBreadcrumb method to log potentially useful events in your own applications:

[Bugsnag leaveBreadcrumbWithMessage:@"Button tapped"];
Bugsnag.leaveBreadcrumb(withMessage: "Button tapped")

Bugsnag will keep track of the time and order of the breadcrumbs and show them on your dashboard.

Additional data can also be attached to breadcrumbs by providing the optional type and metadata parameters. For more information and examples for how custom breadcrumbs can be integrated, see Customizing breadcrumbs.

Session tracking

Bugsnag tracks the number of “sessions” that happen within your application. This allows you to compare stability scores between releases and helps you to understand the quality of your releases.

Sessions are captured and reported by default. This behavior can be disabled using the autoTrackSessions configuration option.

Bugsnag will automatically report a session each time the app is launched or enters the foreground after being in the background for at least 30 seconds.

For more information about controlling session tracking, see Capturing sessions.

Identifying crashes at launch

By default Bugsnag will identify crashes that occur whilst your app is launching, allowing you to prioritize fixing high-impact launch crashes.

Additionally you can use Bugsnag to detect recurrent launch crashes: allowing you to take evasive action in your app, such as resetting data or turning off application features.

Follow the Identifying crashes at launch guide to configure this functionality.

Next steps