Skip to content

iOS

This guide provides instructions for integrating the Coralogix RUM SDK into iOS applications for UIKit and SwiftUI projects. It also details the configuration options, logging functionalities, and best practices for using method swizzling and SwiftUI modifiers to monitor and analyze app performance and user interactions.

Prerequisites

  • iOS: ver. 14 or above

  • Swift: ver. 5.9 or above

  • Xcode: ver. 14 or above

Features

In addition to capturing HTTP requests (instrumentation using URLSession), this SDK can intercept the following telemetry data:

  • Unhandled exceptions, including NSException, NSError, and Error.

  • Custom logs.

  • Crashes, using PLCrashReporter.

  • Page navigation, using method swizzling for UIKit and modifiers for SwiftUI.

Installation

To add the Coralogix SDK to your project using Swift Package Manager:

  1. Open File > Add Packages.

  2. Search for: [email protected]:coralogix/cx-ios-sdk

  3. Select the Up to Next Major Version option.

Initialization

Call the SDK as early in your application lifecycle as possible, ideally in applicationDidFinishLaunching in AppDelegate.

UIKit (AppDelegate)

  1. Use the following code.
import UIKit
import Coralogix

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    var coralogixRum: CoralogixRum?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
            let domain = CoralogixDomain.US2
        let options = CoralogixExporterOptions(
            coralogixDomain: domain,
            userContext: nil,
            environment: "ENVIRONMENT",
            application: "APP-NAME",
            version: "APP-VERSION",
            publicKey: "API-KEY",
            ignoreUrls: [],
            ignoreErrors: [],
            customDomainUrl: "",
            labels: ["String": Any],
            debug: false
        )
        self.coralogixRum = CoralogixRum(options: options)
        return true
    }
}

SwiftUI

Create a SwiftUI project to use Coralogix in your app. It's required if the Swift UI doesn't include AppDelegate or SceneDelegate files.

  1. Use the following code.

import SwiftUI
import Coralogix

@main
struct DemoAppApp: App {
    @State private var coralogixRum: CoralogixRum

    init() {
            let domain = CoralogixDomain.US2
            let options = CoralogixExporterOptions(
            coralogixDomain: domain,
            userContext: nil,
            environment: "ENVIRONMENT",
            application: "APP-NAME",
            version: "APP-VERSION",
            publicKey: "TOKEN",
            ignoreUrls: [],
            ignoreErrors: [],
            customDomainUrl: "",
            labels: ["String": Any],
            debug: false
        )
        self.coralogixRum = CoralogixRum(options: options)
    }

    var body: some Scene {
        WindowGroup {
            ContentView(coralogixRum: $coralogixRum)
        }
    }
}
Refer to the following fields for CoralogixExporterOptions.
PropertyTypeDescriptionRequired
userContextUserContext?Configuration for user context.No
debugBoolTurns on/off internal debug logging.No
ignoreUrls[String]?URLs that partially match any regex in ignoreUrls will not be traced.No
ignoreErrors[String]?A pattern for error messages which should not be sent to Coralogix.No
coralogixDomainCoralogixDomainCoralogix account https://coralogix.com/docs/coralogix-domain/Yes
publicKeyStringCoralogix token, publicly-visible public_key value. This is a required property.Yes
environmentStringSpecifies the environment, such as development, staging, or production.Yes
applicationStringName of the applicationYes
versionStringVersion of the applicationYes
customDomainUrlString?Ignores CoralogixDomain URL and routes all data calls to a specific URL.No
labels[String: Any]?Sets labels that are added to every span.No

Instrumentation

Enable or disable specific instrumentation (see the list below), with the default set to all trues. Each instrumentation controls the data the SDK will track and collect.

  • mobileVitals – Automatically detects and monitors key performance metrics related to application responsiveness and rendering performance. This allows developers to track vital aspects of the app's user experience and performance without manual intervention. The SDK currently supports automatic detection of the following metrics: Frames Per Second (FPS), Warm Start, Cold Start.

  • ANR – Automatically detects Application Not Responsive (ANR) metric.

  • navigation – Identifies user movement between pages (ViewController call) while extracting the view name.

  • custom – Allows developers to define and track custom events, giving insights into specific actions or behaviors in the application that are critical to the business.

  • errors – Captures JavaScript errors, network errors, and other issues in the application. This data helps diagnose and resolve bugs or failures that affect the user experience.

  • network – Monitors all network calls.

  • userActions – Catches user actions, such as button taps, tab activations, and other navigation controllers.

Example

let options = CoralogixExporterOptions(coralogixDomain: CoralogixDomain.US2,
                                               userContext: nil,
                                               environment: "ENVIRONMENT",
                                               application: "APP-NAME",
                                               version: "APP-VERSION",
                                               publicKey: "TOKEN",
                                               ignoreUrls: [], //[".*\\.il$", "https://www.coralogix.com/academy"],
                                               ignoreErrors: [], //[".*errorcode=.*", "Im cusom Error"],
                                               customDomainUrl: nil,
                                               labels: [],
                                               instrumentations: [.navigation: false,
                                                                  .mobileVitals: false,
                                                                  .custom: true,
                                                                  .errors: true,
                                                                  .userActions: true,
                                                                  .network: true],
                                               debug: false)

Integration functions

This section lists public functions used to interact with the Coralogix exporter.

Set user context

Example

public func setUserContext(userContext: UserContext)

Set labels

Example

public func setLabels(labels: [String: Any])

Report errors

Example

public func reportError(exception: NSException)
public func reportError(error: NSError)
public func reportError(error: Error)
public func reportError(message: String, data: [String: Any]?)

Log messages

Send log messages with customized severity levels.

Example

public func log(severity: CoralogixLogSeverity, message: String, data: [String: Any]?)

The CoralogixLogSeverity defines severity levels for logs in the Coralogix system.

CaseRaw ValueSeverity
debug1Debug-level
verbose2Verbose-level
info3Informational
warn4Warning-level
error5Error-level
critical6Critical-level

Example

coralogixRUM.logMessage(severity: .error, message: "An error occurred in the application.")

Shut down the exporter

Shut down the Coralogix exporter and mark it as uninitialized.

Example

public func shutdown()

Method swizzling and SwiftUI modifiers

Use these best practices to dynamically alter the behavior of existing methods at runtime in Swift and Objective-C.

  • Method Swizzling: A technique used in Objective-C and Swift to change the implementation of an existing selector at runtime. Use it for injecting custom behavior without altering the original code.

  • SwiftUI Modifiers: A declarative and safe approach to modifying views through view modifiers, providing better readability and maintainability.

In addition, using CXViewModifier and trackCXView method, you can add custom behavior to views in a SwiftUI-friendly way.

Example

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello, World!")
            .trackCXView(name: "ContentView")
    }
}

Support

Need help?

Our world-class customer success team is available 24/7 to walk you through your setup and answer any questions that may come up.

Feel free to contact us via our in-app chat or by emailing [email protected].