iOS API

Note: iOS Monitoring is currently in open beta.

Instana iOS agent API

The following section describe the usage of the Instana iOS agent. Instana's iOS agent can be used via the Instana class methods explained below.

Setup

Just initialize the Instana iOS agent very early in didFinishLaunchingWithOptions by calling the setup function. If you start Instana delayed, you will see warnings in the console log. Although it is not recommended, you can start Instana with a delay (for example, to load a remote configuration).

static func setup(key: String, reportingURL: URL, httpCaptureConfig: HTTPCaptureConfig = .automatic)

Parameters

Parameter
Description
key (String) The Instana monitoring configuration key.
reportingURL (URL) The URL pointing to the Instana instance to which to the send monitoring data to.
httpCaptureConfig (HTTPCaptureConfig, optional) Default: HTTP requests and responses will be captured automatically. You can also disable automatic monitoring by using manual as capture config. To completely turn off http session monitoring you can pass none

Example

import InstanaAgent

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
    Instana.setup(key: "<Your Instana Key>", reportingURL: URL(string: "<Your Instana instance URL>")!)
    ....
    return true
}

The example above uses the default automatic http capture configuration. To change the httpCaptureConfig you can call:

Instana.setup(key: <Your Key>, reportingURL: <Your Instana URL>, httpCaptureConfig: .manual)

Current Configuration

The Instana class object has some properties to retrieve the current configuration setup:

Property
Description
key (String, optional) The Instana monitoring configuration key.
reportingURL (URL, optional) The URL pointing to the Instana instance to which to the send monitoring data to.

Example

let key = Instana.key
let url = Instana.reportingURL

Session Identifier

Each Instana agent instance has an unique session identifier you could use for other purposes in your app.

Property
Description
sessionID (String, optional) The current session identifier. This session id will be created within the setup process.

Example

let sessionID = Instana.sessionID

Automatic HTTP monitoring

By default HTTP sessions will be be captured automatically. The Instana iOS agent uses Foundation's NSURLProtocol to monitor http requests and responses. To observe all NSURLSession automatically with NSURLProtocol some method swizzling in the NSURLSession is necessary. To opt-out automatic HTTP session monitoring you must capture every request & response manually (see below).

Manual HTTP monitoring

To capture HTTP sessions manually you must setup Instana by passing the httpCaptureConfig: .manual and use the corresponding functions described below.

Start Capture

This function returns the HTTPMarker which you need later when the request has been completed.

static func startCapture(_ request: URLRequest?, viewName: String? = nil) -> HTTPMarker
Parameters
Parameter
Description
request (URLRequest, optional) The URLRequest to capture.
viewName (String, optional) Optional name of the visible view related to this request

Returns: HTTP marker to set the response size, call the finish or error state when the request has been completed.

Finish Capture

Once the request has been completed you must call finish with the response on the HTTPMarker and an optional Error

func finish(response: URLResponse?, error: Error?)

Cancel Capture

Invoke this method on the HTTPMarker if the request has been canceled before completion. The state will be set to failed internally with an NSURLErrorCancelled when calling cancel.

func cancel()

Set HTTP response size

Invoke this method on the HTTPMarker when the response size has been determined.

func set(responseSize: Instana.Types.HTTPSize)
Parameters
Parameter
Description
responseSize (HTTPSize) The httpSize object that contains headerBytes, bodyBytes, bodyBytesAfterDecoding

Note: Make sure you don't call any methods on the HTTPMarker after you called finish or cancel

HTTP response size

You can create the HTTPMarker.Size with the following initializer:

init(response: URLResponse, transactionMetrics: [URLSessionTaskTransactionMetrics]?)
Parameters
Parameter
Description
response (URLResponse) The URLResponse object
transactionMetrics ([URLSessionTaskTransactionMetrics], optional) An optional array with URLSessionTaskTransactionMetrics

You can also create the HTTPMarker.Size object by passing the size values directly as parameter

HTTPMarker.Size(header: Instana.Types.Bytes, body: Instana.Types.Bytes, bodyAfterDecoding: Instana.Types.Bytes)

Complete manual HTTP monitoring example

let marker = Instana.startCapture(request, viewName: "User: Details")
URLSession.shared.dataTask(with: request) { data, response, error in
    marker.finish(response: response, error: error)
}.resume()

You can also set the HTTP response size manually via the URLSessionDelegate like the following example:

func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
    guard let response = task.response else { return }
    marker.set(responseSize: HTTPMarker.Size(response: response, transactionMetrics: metrics.transactionMetrics))
}

Views

Instana can segment app metrics by logical views. To do so, it needs a hint what view the user is currently looking at. This view name can be set via the setView(name: String). The view name will be attached to all monitored beacons until you call setView again with another name. Generally speaking, we recommend not to use technical or generic names like the Class (i.e. WebViewController) to define views. We recommend the usage of readable names for views. For example product detail page or payment selection. This will result in fewer pages which will have a direct relation to actually existing code. We recommend to set the view name in viewDidAppear. Setting the view name will also enable Instana to track page transitions in addition to page loads. The view name gets updated automatically when your app changes the state (e.g. from active to inactive or background). The view name will be ro Inactive when your app is in the inactive state (when receiving a SMS) and will be set to Background once your app leaves the foreground.

static func setView(name: String)

Parameters

Parameter
Description
name (String) The name of the view.

Example

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    Instana.setView(name: "User: Details")
}

To get the current view name you can use the class variable viewName. The value for view name might be Inactive or Background depending on your app state.

Property
Description
viewName (String, optional) The current view name set via setView(name:).

Example

let viewName = Instana.viewName

Identifying Users

User-specific information can optionally be sent with data transmitted to Instana. This information can then be used to unlock additional capabilities such as:

  • calculate the number of users affected by errors,
  • to filter data for specific users and
  • to see which user initiated a view change or HTTP request.

By default, Instana will not associate any user-identifiable information to beacons. Please be aware of the respective data protection laws when choosing to do so. We generally recommend identification of users via a user ID. For Instana this is a completely transparent String that is only used to calculate certain metrics. userName and userEmail can also be used to have access to more filters and a more pleasant presentation of user information.

In cases in which you are handling anonymous users and thus don't have access to user IDs you could alternatively use session IDs. Session IDs are not as helpful as user IDs when filtering data but they are a good indicator to calculate affected/unique user metrics. We recommend setting a user name such as Anonymous to have a clear differentiation between authenticated and unauthenticated users. Session IDs can be sensitive data (depending on the framework/platform used). Please consider hashing session IDs to avoid transmitting data to Instana that can grant access.

It is important to note that data already transmitted to Instana's server cannot be retroactively updated. For this reason it is important to call this API as soon as possible in the app launch process.

static func setUser(id: String, email: String?, name: String?)

Parameters

Parameter
Description
id (String) An identifier for the user.
email (String, optional) The user's email address.
name (String, optional) The user's name.

You can pass nil for values you don't want to set.

Example

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
     Instana.setup(key: InstanaKey, reportingURL: InstanaURL)
     Instana.setUser(id: someID, email: "[email protected]", name: "John")
     return true
}

Meta data

Meta data information that will be attached to the transmitted data. Consider using this to track UI configuration values, settings, feature flags… any additional context that might be useful for analysis. You should set the meta data in the app launch process to assign the key/values to all transmitted data.

static func setMeta(value: String, key: String)

Parameters

Parameter
Description
value (String) The value of the key-value pair you want to add as meta data.
key (String) The key of the key-value pair you want to add as meta data.

Example

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    Instana.setup(key: InstanaKey, reportingURL: InstanaURL)
    Instana.setMeta(value: "ReactNative", key: "Platform")
    Instana.setMeta(value: "DEBUG", key: "Environment")
    return true
}

Excluding URLSession from monitoring

You can ignore a custom URLSession from being monitored by the Instana iOS agent.

static func ignore(_ session: URLSession)

Parameters

Parameter
Description
session (URLSession) URLSession to be ignored from monitoring.

Example

let session = URLSession(configuration: .default)
Instana.ignore(session)

Excluding URLs from Monitoring

You can ignore URLs to reject that match with the given regular expressions to prevent transmission to Instana. A good example for usage of this function would be to ignore all HTTP requests that contain any sensitive data like a password.

static func setIgnoreURLs(matching regex: [NSRegularExpression])

Parameters

Parameter
Description
regex ([NSRegularExpression]) An array of NSRegularExpression objects matching the URLs you want to ignore.

Example

let regex = try! NSRegularExpression(pattern: "/.*(&|\?)password=.*/i")
Instana.setIgnoreURLs(matching: [regex])

That examples ignores all URLs that contain password in the query.

Alternatively you can ignore full URLs like:

Instana.setIgnore(urls: [URL(string: "https://www.example.com")!])

Report Custom Events

Custom events enable reporting about non-standard activities, important interactions and custom timings to Instana. This can be especially helpful when analyzing uncaught errors (breadcrumbs) and to track additional performance metrics.

static func reportEvent(name: String, timestamp: Instana.Types.Milliseconds? = nil, duration: Instana.Types.Milliseconds? = nil, backendTracingID: String? = nil, error: Error? = nil, meta: [String: String]? = nil, viewName: String? = Instana.viewName)

Parameters

Parameter
Description
name (String) Defines what kind of event has happened in your app that should result in the transmission of a custom beacon.
timestamp (Int64, optional) The timestamp in milliseconds when the event has been started. If you don't provide a timestamp, we assume now as timestamp. In case you don't provide a timestamp, but set a duration, we calculate a timestamp by substracting the duration from now. (timestamp = now - duration)
duration (Int64, optional) The duration in milliseconds of how long the event lasted. Default is zero
backendTracingID (String, optional) Identifier to create a backend trace for this event.
error (Error, optional) Error object to provide additional context.
meta ([String: String], optional) Key - Value data which can be used to send metadata to Instana just for this singular event
viewName (String, optional) You can pass a String to group the request to a view. If you send explicitly nil, the viewName will be ignored. Alternatively you can leave out the parameter viewName to use the current view name you did set in setView(name: String))

Examples

Instana.reportEvent(name: "Event-Name")
Instana.reportEvent(name: "Event-Name", viewName: "User: Details")
Instana.reportEvent(name: "Event-Name", timestamp: 1590149955086, duration: 124842, backendTracingID: "some-id", error: NSError(domain: "Some", code: -1, userInfo: nil), meta: ["Key": "Value"], viewName: "User: Details")