OneAgent SDK for iOS
Use the OneAgent SDK for iOS to report additional details about the user sessions in your mobile app. The OneAgent SDK for iOS allows you to create custom actions, measure web requests, report errors, and tag specific users. The sections below explain how to enable these capabilities.
For iOS, the OneAgent SDK is available automatically once you add the Dynatrace CocoaPod to your project. You can use the OneAgent SDK for iOS in Swift and Objective-C.
Start OneAgent
To disable the automatic OneAgent startup, set the DTXAutoStart
configuration key to false
in your app's Info.plist
file:
<key>DTXAutoStart</key><false/>
After that, you can start OneAgent manually using either the Info.plist
configuration or the passed configuration dictionary.
We recommend that you start OneAgent as early as possible, for example, in applicationWillFinishLaunching
.
Start OneAgent with Info.plist
configuration
If you want to start OneAgent with the configuration from the Info.plist
file, use the startupWithInfoPlistSettings
API call.
Start OneAgent with passed config dictionary
If you want to start OneAgent with the passed configuration dictionary, use the startupWithConfig
API call. Configuration keys for the dictionary are the same as for the Info.plist
file, and you can also find them in the Dynatrace.h
header file shipped with OneAgent.
The DTXApplicationID
and DTXBeaconURL
configuration keys are always required.
There might be more parameters that you need to provide. Check the instrumentation wizard in Dynatrace to learn which parameters and values to pass.
Create custom actions
You can define and report custom actions. After you start them, enhance them with additional information before finally closing them.
If you need to change an autogenerated user action, see Modify and cancel autogenerated actions.
When the user opt-in mode is enabled for your application, it might affect user tagging and reporting of custom events, user actions, values, and errors. The exact data types not reported to Dynatrace depend on the data collection level set by a particular user. For details, refer to Data collection levels.
Start and close custom actions
The code snippet below shows how to start and close a custom action. Note that OneAgent discards all action-related monitoring data when the custom action isn't closed. Timing is measured automatically.
For a mobile custom action or a mobile autogenerated user action, the maximum name length is 250 characters.
The maximum duration of a mobile custom action is 9 minutes.
If a custom action takes longer than 9 minutes and is not closed, such an action is discarded and not reported to Dynatrace.
You can perform the following monitoring operations with a custom action:
Create child actions
Child actions are similar to parent actions. When a parent action is closed, OneAgent automatically closes all child actions of the parent action.
The code snippet below shows how to start an action as the child of another action.
For a mobile custom action or a mobile autogenerated user action, the maximum name length is 250 characters.
There's no limit on the number of child actions attached to a parent action. However, note that you can have only nine levels of child actions—you can create one parent action and nine levels of child actions (when child action A is added to a parent action, child action B is added to child action A, child action C is added to child action B, and so on). Also, refer to User session structure for individual user.
Child actions are not displayed on the user session details page, but you can view them on the waterfall analysis page for a parent action to which these child actions are attached. Even though the child action nesting is not fully preserved in the waterfall analysis view and all child actions are displayed as child actions of level 1, you can still grasp the action nesting from the timings.
User action sample
The following code snippet shows a sample manual instrumentation.
Cancel actions
OneAgent for iOS version 8.229+
You can cancel a custom action or an autogenerated user action. Canceling an action discards all data associated with it: all reported values are discarded and all child actions are canceled.
You cannot cancel a closed action, so calling cancel
/cancelAction
after leave
/leaveAction
is impossible for the same action. The same goes for closing a canceled action: you cannot call leave
/leaveAction
after using cancel
/cancelAction
for the same action.
Report an event
With reportEvent
, you can report a specific event. The event must belong to an existing custom action or an autogenerated user action. Reported events are displayed in the user action waterfall analysis.
If you want to report standalone events with lots of additional information, see Report a business event.
When the user opt-in mode is enabled for your application, it might affect user tagging and reporting of custom events, user actions, values, and errors. The exact data types not reported to Dynatrace depend on the data collection level set by a particular user. For details, refer to Data collection levels.
Report an error
With reportError
, you can report a specific event as an error.
There are two options for reporting an error.
- Report it as part of an action (either a custom action or an autogenerated user action)
- Report it as a standalone error, which is generated as a global event that is not tied to a specific action
Reported errors (both standalone and "attached" to a user action) are displayed on the user session details page and multidimensional User action analysis page. Reported errors that are part of a user action are also displayed in the user action waterfall analysis.
You can report an error with an error code, an exception, or an NSError
.
When the user opt-in mode is enabled for your application, it might affect user tagging and reporting of custom events, user actions, values, and errors. The exact data types not reported to Dynatrace depend on the data collection level set by a particular user. For details, refer to Data collection levels.
Report a value
The reportValue
method allows you to report key-value pairs of metadata that you can later view in the Dynatrace web UI and convert into user action and user session properties. The reported values must be part of a user action.
You can report values of the following data types:
int
double
string
To view the reported values in the Dynatrace web UI, go to the details of the user action that should contain that metadata and scroll down to the Reported values section.
To add action and session properties based on the reported values and then use these properties to create powerful queries, segmentations, and aggregations, see Define user action and user session properties for mobile applications.
When the user opt-in mode is enabled for your application, it might affect user tagging and reporting of custom events, user actions, values, and errors. The exact data types not reported to Dynatrace depend on the data collection level set by a particular user. For details, refer to Data collection levels.
Report a business event
OneAgent for iOS version 8.253+
With sendBizEvent
, you can report business events. These are standalone events, as Dynatrace sends them separately from user actions or user sessions.
Business events are only captured for monitored sessions. When OneAgent is disabled either through a special flag or due to cost and traffic control, business events are not reported for such sessions. Note that this behavior might be subject to change in the future, potentially allowing business events to be sent to Dynatrace regardless of session monitoring.
For additional details on business events, refer to Business Analytics.
Measure web requests
To track web requests, OneAgent adds the x-dynatrace
HTTP header with a unique value to each request. This is required to correlate the server-side monitoring data to the corresponding mobile web request. Additionally, the timing values from the mobile side are measured.
OneAgent for iOS automatically times web requests made using NSURLRequest
, NSURLConnection
, NSURLSession
, NSURLProtocol
, NSString
, WKWebView
, or NSData
. However, you have to manually instrument requests in the following cases:
- When the automatic instrumentation of web requests is disabled
- When the requests of a third-party framework aren't instrumented
- When you need to report non-HTTP(S) requests
Which instrumentation type to use
For HTTP(S) requests, you cannot combine automatic and manual web request instrumentation. However, you can use automatic instrumentation for HTTP(S) requests and manual instrumentation for non-HTTP(S) requests such as WebSocket or gRPC requests.
The table below explains which type of request instrumentation to use depending on which request types your app has. It also shows whether you should disable the automatic request instrumentation.
DTXInstrumentWebRequestTiming
true
false
false
(optional)true
false
Parent action of web requests
There is a predefined order that OneAgent for iOS follows to determine the parent of a web request event, which affects how web requests are listed in the waterfall analysis.
Automatic web request instrumentation
- If there is an active custom action started on the same thread as a web request, this action is the parent action.
- If there is no active custom action, but there is an active autogenerated action, then the autogenerated action (for example,
Touch on...
) is the parent action. This includes theLoading ...
autogenerated action. - If OneAgent cannot find an active action, then the web request event is a root level event that doesn't have a parent action.
Manual web request instrumentation
- If no parent action is provided (
Dynatrace.getRequestTagValue(for: url)
), then the behavior to find the parent action is the same as for automatic web request timing. - If a parent action is provided (
childAction?.getTagFor(url)
), then this action is the parent action.
Currently, you cannot view standalone web request events of a root level in Session Segmentation.
Example: Simplified manual web request instrumentation
import UIKitimport WebKitimport Dynatraceclass ViewController: UIViewController {override func viewDidLoad() {super.viewDidLoad()let wkWebView = WKWebView(frame: self.view.frame)self.view.addSubview(wkWebView)manualTaggingDemo(wkWebView: wkWebView)}func manualTaggingDemo(wkWebView: WKWebView) {let parentAction = DTXAction.enter(withName: #function)let url = URL(string: "https://www.dynatrace.com")downloadRequest(url: url!, wkWebView: wkWebView, parentAction: parentAction) //as this is async parent action should be left when request is done}func downloadRequest(url: URL, wkWebView: WKWebView, parentAction: DTXAction?) {let childAction = DTXAction.enter(withName: #function, parentAction: parentAction) //add child action to see method call tracelet session = URLSession.sharedlet request = NSMutableURLRequest(url: url)request.httpMethod = "GET"request.cachePolicy = .reloadIgnoringCacheDatavar webrequestTiming: DTXWebRequestTiming?//if let dynatraceHeaderValue = Dynatrace.getRequestTagValue(for: url) { //let agent decide which action it uses as parent (last created action)if let dynatraceHeaderValue = childAction?.getTagFor(url) { //provide parent actionlet dynatraceHeaderKey = Dynatrace.getRequestTagHeader() //this could be cached as it always is x-dynatracerequest.addValue(dynatraceHeaderValue, forHTTPHeaderField: dynatraceHeaderKey)webrequestTiming = DTXWebRequestTiming.getDTXWebRequestTiming(dynatraceHeaderValue, request: url)}let task = session.downloadTask(with: request as URLRequest) {(location, response, error) indefer {parentAction?.leave() //leave parent action when request finished - all child actions are automatically left on leaving parent}guard let _:URL = location, let _:URLResponse = response, error == nil else {webrequestTiming?.stop("failed") //stop webrequest timing in error casereturn}let urlContents = try! String(contentsOf: location!, encoding: .utf8)guard !urlContents.isEmpty else {webrequestTiming?.stop("empty content") //stop webrequest timing in error casereturn}webrequestTiming?.stop((response as! HTTPURLResponse).statusCode.description) //stop webrequest when request finishedDispatchQueue.main.async {wkWebView.loadHTMLString(urlContents, baseURL: nil)}}webrequestTiming?.start() //start webrequest timingtask.resume()}}
Monitor non-HTTP(S) requests
OneAgent for iOS does not support auto-instrumentation of non-HTTP(S) requests. If you need to report requests such as a WebSocket request (starts with ws://
or wss://
), check the following code samples.
If you have only non-HTTP(S) requests, you may disable the automatic request instrumentation, but you don't have to.
If you have both HTTP(S) and non-HTTP(S) requests and HTTP(S) requests are auto-instrumented, don't disable automatic request instrumentation.
Specifying the number of sent and received bytes (also known as request and response sizes) when manually reporting a web request is only possible for OneAgent for iOS version 8.285+. This additionally provided information is then shown in the Dynatrace web UI on the following pages.
- On the web requests details page (accessible via the Top providers section)—only request size (bytes sent) is shown
- On the User action analysis page for web requests attached to user actions—both bytes sent and received (request and response sizes) are shown
Disable automatic request instrumentation
To disable the automatic web request instrumentation, set the DTXInstrumentWebRequestTiming
configuration key to false
.
Tag specific users
You can tag each user of your mobile apps with a unique user name. This enables you to search and filter specific user sessions and analyze individual user behavior over time. For more details, see User tagging.
The following steps explain how to manually tag an individual user via the Dynatrace API.
OneAgent for iOS version 235+ Sessions split due to idle or duration timeout are re-tagged automatically.
When OneAgent ends a tagged session because the session duration has reached its set limit or due to the user's inactivity, the subsequent session is re-tagged automatically. You don't need to provide the user identification information again.
However, note that OneAgent does not re-tag the subsequent session in the following cases:
- When you explicitly end a tagged user session via
endVisit
- When the user or the mobile operating system closes or force stops the app
- When OneAgent ends the current user session and generates a new session after the privacy settings have been changed
See User sessions > Session end to learn when OneAgent ends a mobile user session.
When the user opt-in mode is enabled for your application, it might affect user tagging and reporting of custom events, user actions, values, and errors. The exact data types not reported to Dynatrace depend on the data collection level set by a particular user. For details, refer to Data collection levels.
End a session
You can force a session to end via the Dynatrace API. This also closes all open actions and starts a new session.
Configure data privacy (opt-in mode)
With user opt-in mode, each user of your application can set their data privacy preferences and decide whether they want or don't want to share their information. When the opt-in mode is enabled, you need to ask each user for permission to capture their data; then, you store their data privacy preferences. For details, see User opt-in mode.
Enable user opt-in mode
To activate the user opt-in mode, add the DTXUserOptIn
configuration key to your app's Info.plist
file:
<key>DTXUserOptIn</key><true/>
Change user's data privacy preferences
The following code examples show you how to adjust the data privacy preferences based on the decision of a particular user.
The possible values for the data collection level are as follows:
.off
DTX_DataCollectionOff
.performance
DTX_DataCollectionPerformance
.userBehavior
DTX_DataCollectionUserBehavior
OneAgent persists the data privacy preferences and automatically applies them when the application is restarted. Each time the user changes the data collection level, OneAgent generates a new session with new settings. Ensure that you don't wrap this API method with a user action; otherwise, OneAgent won't be able to attach the user action to the correct session.
Retrieve user's data privacy preferences
You can also use the same properties to retrieve the data privacy preferences of a particular user.
User action naming
To construct user action names, OneAgent captures the control title from UIButton
by evaluating the following order of APIs or fields and stopping once it receives a valid text:
titleLabel.attributedText
attributedTitleForState:UIControlStateNormal
accessibilityLabel
If none of these produce usable text, OneAgent sets the control title to the default Button
value.
For cells, the behavior is similar: a heuristic is used to determine the most prominent label in the cell, and OneAgent uses that text in a user action name.
Use custom control titles
You can override the captured control titles for UIControl
, UITableViewCell
, and UICollectionViewCell
. This allows you to change control titles or hide them for privacy reasons.
If you provide an empty string, OneAgent uses the control type in a user action name, for example, Touch on Button
. Providing nil
resets the control title to the default one.
If you want to get rid of control titles in all user actions at once, see Mask user actions.
Modify autogenerated actions
OneAgent for iOS creates user actions based on interactions of your application's users. These actions are different from custom actions and are sometimes called autogenerated actions. We also refer to them as user actions.
Using the OneAgent SDK for iOS, you can modify or even cancel these autogenerated actions.
If you want to avoid capturing personal information for all user actions at once, see Mask user actions.
Modify a specific user action
OneAgent for iOS version 8.215+
With Dynatrace.modifyUserAction
, you can modify the current user action. You can change the user action name and report events, values, and errors. You can also cancel a user action.
Allowed operations on the returned user action object are as follows:
getName
setName
reportEvent
reportValue
reportError
- OneAgent for iOS version 8.241+
cancelAction
/cancel
You can modify a user action only while it is still open. If the user action times out before it is modified, the modification has no effect. Calling leave
on this object also has no effect.
For a mobile custom action or a mobile autogenerated user action, the maximum name length is 250 characters.
Modify any user action
OneAgent for iOS version 8.241+
You can modify autogenerated user actions via Dynatrace.modifyUserAction
. However, you can do that only for a specific user action, and you usually should know whether this user action is still open or not.
To overcome these limitations, we introduced a feature that allows you to receive a callback for every newly created user action. With this approach, you are notified about every new autogenerated user action, so you get a chance to update the user action name as well as report events, values, and errors. You can also cancel a user action.
You can register a callback that is invoked for each autogenerated user action. You can set the callback anywhere in the application at any point in time.
Any previously registered callback is overwritten by a subsequent call to the API method.
Allowed operations are as follows:
getName
setName
reportEvent
reportValue
reportError
cancelAction
/cancel
For a mobile custom action or a mobile autogenerated user action, the maximum name length is 250 characters.
Mask user actions
OneAgent for iOS version 8.249+
By default, user action names are derived from UI element titles, for example, button or table cell titles. In rare circumstances, email addresses, usernames, or other personal information might be unintentionally included in user action names. This happens when this information is included in parameters used for control titles, resulting in user action names such as Touch on Account 123456
.
If such personal information appears in your application's user action names, enable user action masking. OneAgent will replace all Touch on <control title>
action names with the type of the control that the user touched, for example:
Touch on Account 123456
>Touch on Button
Touch on Transfer all amount
>Touch on Switch
Touch on Country
>Touch on TableCell
To enable user action masking, set the DTXUIActionNamePrivacy
configuration key to true
in your app's Info.plist
file.
<key>DTXUIActionNamePrivacy</key><true/>
User action masking doesn't change custom control titles.
If you want to change names only for certain controls or certain user actions, use one of the following settings:
- Use custom control titles to override the UI element titles captured by default
- Modify autogenerated actions to change user action names
- Set naming rules (mobile app settings > Naming rules) to configure user action naming rules or extraction rules