iOS SDK Error Analysis

Last updated on

Introduction

Prerequisites

Contentsquare SDK is included

You must include the Contentsquare SDK first using the same integration method and understand how the SDK works.

Update to the latest SDK version

In order to enable Error Analysis in your app and get the most stable version, it is required to upgrade the SDK to its latest version.

Screen tracking implemented

Tracking will start at the 1st screenview event, it is required to have screen tracking implemented. Make sure to follow the iOS Track screens sections.

If you are in the process of implementing the SDK for the 1st time (or choose to take this update as an opportunity to review your Privacy related implementation), make sure to follow the iOS Privacy section and use the Opt-in API to get the user consent, otherwise no data will be collected.

Get Started

Add Contentsquare Error Analysis to your app

How to include it

You should include the Contentsquare SDK first and use the same integration method.

[tab] Using Swift Package Manager

  1. In Xcode, Same as Contentsquare SDK, Add the following link via File > Add Packages…:

    https://github.com/ContentSquare/CS_iOS_SDK.git
    
  2. In your targets’ General settings tab, in the Frameworks, Libraries, and Embedded Content section, add ContentsquareErrorAnalysisModule.

[tab] Using Carthage

Add the following line to your Cartfile:

Cartfile
binary "https://raw.githubusercontent.com/ContentSquare/CS_iOS_SDK/master/carthage/ContentsquareErrorAnalysisModule.json"

Then run:

carthage update --platform ios --use-xcframeworks

Drag and drop ContentsquareModuleErrorAnalysis.xcframework from the Carthage/Build folder to your targets’ General settings tab, in the Frameworks, Libraries, and Embedded Content section.

[tab] Using CocoaPods

Our SDK can be linked dynamically or statically:

Dynamic linking

Dynamic linking is the default behavior with use_frameworks!, Add the following line to your Podfile:

Podfile
pod 'CS_ErrorAnalysis'
Static linking

If you specify static linking in your Podfile with use_frameworks! :linkage => :static, Add the following line to your Podfile:

Podfile
pod 'CS_ErrorAnalysis_STATIC'

[tab] Manual Integration

Our SDK can be linked dynamically or statically:

Dynamic linking
Get the manual integration framework
  1. Go to the iOS SDK GitHub repository.
  2. Find the newest version available (unless instructed otherwise by your CS contact).
  3. Under Assets you should be able to find ContentsquareErrorAnalysisModuleDynamicManually.xcframework.zip, download the file.
Include the framework
  1. Unzip ContentsquareErrorAnalysisModuleDynamicManually.xcframework.zip and you should see ContentsquareErrorAnalysisModule.xcframework:
  2. Copy ContentsquareErrorAnalysisModule.xcframework to any folder in your project.
  3. In your target -> General -> Frameworks, Libraries and Embedded Content, add ContentsquareErrorAnalysisModule.xcframework by clicking "+" -> "Add Other..." -> "Add Files...".
  4. Clean build folder and run.
Static linking
Get the manual integration framework
  1. Go to the iOS SDK GitHub repository.
  2. Find the newest version available (unless instructed otherwise by your CS contact).
  3. Under Assets you should be able to find ContentsquareErrorAnalysisModuleStaticManually.xcframework.zip, download the file.
Include the framework
  1. Unzip ContentsquareErrorAnalysisModuleStaticManually.xcframework.zip and you should see ContentsquareErrorAnalysisModule.xcframework:
  2. Copy ContentsquareErrorAnalysisModule.xcframework to any folder in your project.
  3. In your target -> General -> Frameworks, Libraries and Embedded Content, add ContentsquareErrorAnalysisModule.xcframework by clicking "+" -> "Add Other..." -> "Add Files...".
  4. Clean build folder and run.

Start the SDK

You do not need to do anything to start the Error Analysis SDK, it will start itself with Contentsquare SDK.

Validate SDK integration

When the SDK starts, you should see a log like this one:

// success case
Contentsquare Error Analysis v[SDKVersionNumber] starting in app:: [your.bundle.id]

// fail case
// << No public fail log

Sample app

For best implementation practices of our library, explore the Contentsquare for iOS sample app.

API Errors

Automatic network inspection

API Errors automatically collects failed network requests that use URLSession.

Add custom monitoring for specific network requests

The API Errors automatically collects most network requests for your app. However, some requests might not be collected or you might use a different library to make network requests. In these cases, you can use the following API HTTPMetric to manually collect data.

[tab] Swift

guard let url = URL(string: "https://www.apple.com") else { return }
let request: URLRequest = URLRequest(url: url)
let metric = HTTPMetric(request: request)
let session = URLSession(configuration: .default)
let dataTask = session.dataTask(with: request) { (urlData, response, error) in
    if let httpResponse = response as? HTTPURLResponse {
        metric.setStatusCode(httpResponse.statusCode)
    }
    metric.stop()
}
dataTask.resume()

[tab] Objective-C

NSURL *url = [NSURL URLWithString:@"https://www.apple.com"];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
HTTPMetric *metric = [[HTTPMetric alloc]initWithRequest:request];
NSURLSession *session = [NSURLSession sessionWithConfiguration:NSURLSessionConfiguration.defaultSessionConfiguration];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
    [metric setStatusCode:httpResponse.statusCode];
    [metric stop];
}];
[task resume];

Removing Personal Data in request URL path

By default, the API Errors feature collects the URL path of the failed API requests. To prevent the collection of Personal Data in the URL path, you can rewrite the request URL path with the setURLMaskingPatterns SDK API.

/// This API must called at App launch.
public static func setURLMaskingPatterns(_ patterns: [String])

Simply replace a step of the path - meaning between two slashes (/) - containing Personal Data with a variable:

  • becomes CS_ANONYMIZED_USER_ID
  • becomes CS_ANONYMIZED_ADDRESS

Example

ErrorAnalysis.setURLMaskingPatterns([
    "https://www.api.com/users/:user_id/address/:address"
])
URL before anonymizationURL after anonymization
https://www.contentsquare.com/users/123/address/castle+blackhttps://www.contentsquare.com/users/CS_ANONYMIZED_USER_ID/address/CS_ANONYMIZED_ADDRESS

Debugging and Logging

If in-app features are enabled, a log should appear with the details of the event (see iOS Debugging and Logging section for more details):

CSLIB ℹ️ Info: API Error - GET 401 https://api.client.com

How API Errors works

Initialization

The way our SDK works is by auto-starting with the application launch and automatically collects failed network requests that use URLSession.

Configuration

Once started, our SDK fetches its config from our servers. It will start collecting data from network events if the API Errors setting is enabled in the config (this is handled by the Contentsquare team).

Tracking

The SDK monitors only the API Errors with response code above 400, and generates analytics data. These events are then locally stored, and eventually sent to our servers in batches.

Sending data

For each network error, a new event will be sent in analytics and Session Replay data. Check the following sections to learn more about how data is processed and sent:

API Troubleshooting Details

API Errors troubleshooting details enables you to collect more information about API errors so you can troubleshoot errors faster.

With this feature you will be able to see three types of additional API error details in the Event Stream of Session Replay.

  • The HTTP headers of the request and the response.
  • The body (the data sent by the request or received in the response).
  • The query parameters of the request endpoint (of the URL of the information you request for).

See API Troubleshooting Details for more details.

Mask API Error By Template URL

This method will mask URLs of failing API calls to URLs that match the template URL.

Use colon (:) to indicate a dynamic parameter.

[tab] Swift

ErrorAnalysis.setURLMaskingPatterns([
    "https://<domain>/:status_code/person/:person_id/store/:store_id"
])

[tab] Objective-C

[ErrorAnalysis setURLMaskingPatterns: @[
    @"https://<domain>/:status_code/person/:person_id/store/:store_id"
]];

Collected data points

Only network calls with error (response code above 400) will be collected. Here is the list of data collected:

  • URL (without query strings)
  • HTTP method
  • Response code
  • Timestamp of the request
  • Timestamp of the response
  • HTTP headers of the request
  • HTTP headers of the response
  • HTTP body of the request
  • HTTP body of the response
  • Query parameters of the request endpoint

Known limitations and recommendations

Automatic collection limitations

The auto collection doesn't work for the following methods:

func data(for request: URLRequest) async throws -> (Data, URLResponse)
func data(from url: URL) async throws -> (Data, URLResponse)
func upload(for request: URLRequest, from bodyData: Data) async throws -> (Data, URLResponse)
func upload(for request: URLRequest, fromFile fileURL: URL) async throws -> (Data, URLResponse)
func download(for request: URLRequest) async throws -> (URL, URLResponse)
func download(from url: URL) async throws -> (URL, URLResponse)
 
func downloadTask(withResumeData: Data) -> URLSessionDownloadTask
func downloadTask(withResumeData: Data, completionHandler: (URL?, URLResponse?, Error?) -> Void) -> URLSessionDownloadTask
 
func streamTask(withHostName: String, port: Int) -> URLSessionStreamTask
func streamTask(with: NetService) -> URLSessionStreamTask
 
func webSocketTask(with: URL) -> URLSessionWebSocketTask
func webSocketTask(with: URLRequest) -> URLSessionWebSocketTask
func webSocketTask(with: URL, protocols: [String]) -> URLSessionWebSocketTask

Workaround: For the async methods, use the corresponding Contentsquare methods:

try await URLSession.shared.cs.data(for: request)
try await URLSession.shared.cs.data(from: url)
try await URLSession.shared.cs.upload(for: request, from: data)
try await URLSession.shared.cs.upload(for: request, fromFile: file)
try await URLSession.shared.cs.download(for: request)
try await URLSession.shared.cs.download(from: url)

For other methods, use the custom monitoring APIs.

Conflict with Firebase Performance SDK on auto-collection

API Errors is compatible with Firebase Performance auto-collection, but the HTTP body from the response won't be collected by the Error Analysis SDK.

Workaround: Disable Firebase automatic monitoring:

Performance.sharedInstance().isInstrumentationEnabled = false

It may also not be compatible with other network auto collection tools.

Crash Reporter

Setup Firebase Crashlytics compatibility mode

Based on our test, the Contentsquare Crash Reporter is compatible with Firebase Crashlytics as long as the Contentsquare Crash Reporter is initialized first, otherwise some crashes can be missing in Crashlytics.

You can use this API to launch Firebase Crashlytics after Contentsquare Crash Reporter

ErrorAnalysis.onCrashReporterStart { _ in
    FirebaseApp.configure()
}
[ErrorAnalysis onCrashReporterStart:^(BOOL _) {
    [FIRApp configure];
}];

Upload dSYMs

"When Xcode compiles your source code into machine code, it generates a list of symbols in your app — class names, global variables, and method and function names. These symbols correspond to the file and line numbers where they're defined; this association creates a debug symbol" See Apple's documentation for more details.

When an app crashes, the operating system collects diagnostic information about what the app was doing at the time of crash. Some of the most important parts of the crash report are presented as hexadecimal addresses. To translate those addresses into readable function names and line numbers from your source code, a process called symbolication is used. See Apple's documentation for more details.

In order to symbolicate the crashes reported by a specific version of your app and make them readable, you need to provide the symbol files (dSYMs) that were generated when your app was built.

Build your app with dSYMs

Make sure Xcode is generating dSYMs for your app:

  1. Open your project in Xcode.
  2. Select the project file in the Xcode Navigator.
  3. Select your main target.
  4. Select the Build Settings tab and click All to show all the build settings.
  5. Filter by Debug Information Format.
  6. Set Debug Information Format to DWARF with dSYM File for all the build types you want to generate dSYMs.
  7. Rebuild your main target.

Locate dSYMs

Download dSYMs from the App Store

If you build your main target using bitcode (Bitcode Enabled turned on in build settings) and you uploaded your app's symbols to the App Store, you need to download the dSYMs from the App Store:

  1. Log in to App Store Connect, then select My Apps.
  2. Select your app from the grid.
  3. Select the build you want to download a dSYM for.
  4. Click Build Details > Download dSYM.

In case you use bitcode to build your main target but you didn't upload your dSYMs to the App Store, you need to find your dSYMs on your local machine and restore hidden symbols using the BCSymbolMaps Xcode generates.

Find dSYMs on your local machine

You can find the dSYMs in the .xcarchive directory on disk:

  1. In Xcode, open the Organizer window (Window -> Organizer).
  2. Select your app from the list.
  3. Control-click an archive and select Show in Finder.
  4. A Finder window should appear. Control-click the xcarchive package and select Show Package Contents.
  5. There should be a dSYMs directory that contains the dSYMs generated in Xcode's archiving process. If you use the Download Debug Symbols option from Xcode's organizer, the recompiled bitcode dSYMs are also downloaded to this directory.

Restore hidden symbols using BCSymbolMaps

Restoring hidden symbols using BCSymbolMaps is only required if you built your main target using bitcode (Bitcode Enabled turned on in build settings). If you used bitcode but downloaded the dSYMs from the App Store, the dSYMs will be recompiled and you can skip this step.

To restore hidden symbols you can run the following command:

dsymutil -symbol-map /path/to/archive/BCSymbolMaps /path/to/dsym.dSYM

Get project credentials

Reach out to your Contentsquare contact.

Use script to upload dSYMs

To upload dSYMs to Error Analysis you need to use the provided upload-symbols script. You need to provide the path where the dSYM files are located as a positional argument, and the Project ID, Client ID and Client Secret either as keyword arguments or set them as environment variables.

KeyEnvironment Key
--project-idERROR_ANALYSIS_PROJECT_ID
--client-idERROR_ANALYSIS_CLIENT_ID
--client-secretERROR_ANALYSIS_CLIENT_SECRET

If both are provided, the keyword arguments will prevail over the environment variables.

[tab] Using Swift Package Manager

If you are using SPM to integrate the Error Analysis SDK, the upload-symbols script will be located in the SPM checkout path for the SDK.

To execute the script using keyword arguments, you can use the following command:

${BUILD_DIR%Build/*}SourcePackages/checkouts/CS_iOS_SDK/scripts/upload-symbols <path-to-dSYMs-directory> --project-id <project-id> --client-id <client-id> --client-secret <client-secret>

To use environment variables instead, you can use the following commands:

export ERROR_ANALYSIS_PROJECT_ID=<project-id>
export ERROR_ANALYSIS_CLIENT_ID=<client-id>
export ERROR_ANALYSIS_CLIENT_SECRET=<client-secret>
${BUILD_DIR%Build/*}SourcePackages/checkouts/CS_iOS_SDK/scripts/upload-symbols <path-to-dSYMs-directory>

[tab] Using other dependency managers

If you are using Carthage, CocoaPods or you are manually integrating the Error Analysis SDK, you will need to download the upload-symbols script from the latest SDK release.

  1. Go to the CS_iOS_SDK releases page.
  2. Click on Show all assets located at the bottom of the Assets list of the latest release.
  3. Click on upload-symbols-script.zip.
  4. Unzip the script.
  5. Move the script to your desired location.

At this point, to execute the script using keyword arguments, you can use the following command:

<script-location-path>/upload-symbols <path-to-dSYMs-directory> --project-id <project-id> --client-id <client-id> --client-secret <client-secret>

To use environment variables instead, you can use the following commands:

export ERROR_ANALYSIS_PROJECT_ID=<project-id>
export ERROR_ANALYSIS_CLIENT_ID=<client-id>
export ERROR_ANALYSIS_CLIENT_SECRET=<client-secret>
<script-location-path>/upload-symbols <path-to-dSYMs-directory>

Debugging and Logging

Enabling crash reporting will conflict with any attached debuggers, so make sure a debugger isn't attached when you crash the app. In case a debugger is attached to the device, Crash Reporter won't be initialized and a log will be printed in the console:

CSLIB ℹ️ Info: Debugger present, crash reporter is not initialized

To test if Crash Reporter is working properly, you first need to disconnect your test device or simulator from Xcode debugger:

  • Tap on the Edit scheme... option of your current scheme
  • Disable the Debug executable option in your scheme configuration.
  • Build and run your current scheme.

If Crash Reporter is successfully initialized when you launch your application, you should see a log printed in the console:

CSLIB ℹ️ Info: Crash reporter is initialized

Alternatively, you can detach your application from Xcode debugger by stopping it after is launched. This way Crash Reporter will be initialized and will start reporting crashes, but you won't be able to see the logs printed in the console:

  • Build and run your current scheme.
  • Wait until the app is up and running.
  • Click on Stop running the scheme.
  • Open the app directly from your test device or simulator.

Run your application and force a crash (you can do it by adding a fatalError() in your code). Launch the application again using Xcode and you should see a log printed in the console that indicates that a crash has been detected and sent:

CSLIB ℹ️ Info: Crash event detected and sent for userID: <user-id>, session: <session-number> on screen: <screen-number> - crashID: <crash-id>

How Crash Reporter works

Initialization

Crash Reporter is started automatically and begins to report crashes when your application is launched.

Configuration

Once started, our SDK fetches its configuration from our servers. It will start reporting crashes if the Crash Reporter setting is enabled (this is handled by the Contentsquare team).

Reporting

When a crash occurs, a report is created and stored locally in the device. Once the app is launched again, the report is sent to our servers and then removed from the local storage.

Sending data

For each crash, a new event will be sent to analytics and Session Replay data when the app is launched again after the crash occurred and the network conditions allow for the server to be reached.

Our requests use lowPriority.

Collected data points

Crash Reporter handles multiple types of crashes, including:

  • Mach kernel exceptions
  • Fatal signals
  • C++ exceptions
  • Objective-C exceptions

For each crash we collect information of the application, system, process, threads, stack traces and some other events metadata you can find in collected data points.

Known limitations and recommendations

Compatibility with other crash reporters

Beyond Firebase Crashlytics (see Setup Firebase Crashlytics compatibility mode), the Contentsquare Crash Reporter is not compatible with other crash reporters. For more details, reach out to your Contentsquare contact.

Impact on Performance

We always strive to be non-intrusive, and transparent to the developers of the client app. We apply this rule on the performance as well. These are the technical specifics we can share on performance, if you have any questions feel free to reach out to us.

The following performances results were obtained under the following conditions:

ConditionValue
Device modeliPhone 11 64GB
iOS version16.3.1
Test App built using Xcode version14.3
Test App built with Swift version5.8
PropertyValue
SDK size (installed size, no Bitcode)1.5 MB
Max Ram usage<1.16MB
Max SDK CPU peak on event<4.1%