iOS SDK API guide

Use the iOS SDK API for New Relic Mobile to add custom data. For example:

  • Instrument your own code.
  • Start and stop interaction traces from events in your mobile app.
  • Record custom metrics.
  • Send custom attributes and events to Insights.
  • Track networking from libraries not supported automatically.
  • Set a custom identifier value with Objective-C or Swift to associate user sessions with analysis events and attributes (iOS SDK version 5.9.0 or higher).

Tracing is heavily optimized, but it does impose a performance overhead. Avoid instrumenting methods that are expected to be called hundreds of times.

Install the SDK

Ensure you have your app instrumented with the latest New Relic Mobile SDK by using the instructions at rpm.newrelic.com/mobile.

This document contains the iOS SDK instrumentation requirements for:

For details about the available methods for custom attributes and events you can send to to New Relic Insights, see the iOS SDK API reference. You can also configure feature flags for:

  • Objective-C
  • Swift

Automatically instrumented classes and methods

The following methods (for the listed classes and their sub-classes) are already instrumented by New Relic. You do not need to add custom instrumentation to trace them.

Classes Methods automatically instrumented by New Relic
UIViewController
  • viewDidLoad:
  • viewWillAppear:
  • viewDidAppear:
  • viewWillDisappear:
  • viewDidDisappear:
  • viewWillLayoutSubviews:
  • viewDidLayoutSubviews:
UIImage
  • imageNamed:
  • imageWithContentsOfFile:
  • imageWithData:
  • imageWithData:scale:
  • initWithContentsOfFile:
  • initWithData:
  • initWithData:scale:

NSJSONSerialization

  • JSONObjectWithData:options:error:
  • JSONObjectWithStream:options:error:
  • dataWithJSONObject:options:error:
  • writeJSONObject:toStream:options:error:
NSManagedObjectContext
  • executeFetchRequest:error:
  • processPendingChanges

New Relic Mobile aggregates performance for various methods into summary metrics that appear in New Relic Mobile's Interactions page. Summary categories include:

  • View loading
  • UI layout
  • Database
  • Images
  • JSON
  • Network

Instrument your Objective-C code

To have your own Objective-C code appear in interaction code breakdowns and timelines, add a _START call to the beginning of your method and a _STOP call to the end of it.

Always include a _STOP for each _START, and only include one set of these commands in a given method. The trace system will automatically pick up the class and method name, and report performance metrics for your method to New Relic Mobile.

- (void)myMethod
{
  NR_TRACE_METHOD_START(0);

  // … existing code

  NR_TRACE_METHOD_STOP;
}

If you are not using ARC, use this version of the _STOP macro to avoid memory leaks:

NR_NONARC_TRACE_METHOD_STOP;

If you want your method’s performance to be included in the summary data on the APM Overview page, pass one of the NRTraceType enum values into the _START macro; for example:

NR_TRACE_METHOD_START(NRTraceTypeDatabase);
Create and complete interactions

By default, an interaction starts when a view controller is pushed. To manually start an interaction with Objective-C, use these API calls:

NSString* uniqueIdentifier = NR_START_NAMED_INTERACTION(@"name");

This macro will automatically begin tracking the name interaction trace from the current line. It will also complete any previously running interaction. It returns a unique identifier that can be used to complete that interaction by using this API call:

NR_INTERACTION_STOP(uniqueIdentifier);

This macro will complete the interaction associated with the uniqueIdentifier if that interaction has not already completed automatically. You do not need to call this method.

Rename a default interaction

By default, the iOS agent will start an interaction trace when a new view controller is displayed. The interactions are named using the format Display <ViewController>. To change these default names with Objective-C, implement the - (NSString*) customNewRelicInteractionName instance method in your view controller, where the string returned becomes the interaction's name.

Set a custom application version

The New Relic iOS SDK allows you to set a custom application version string with Objective-C. Instead of using the string defined in CFBundleShortVersionString, call the +[NewRelic setApplicationVersion:] method and pass along the custom application version before calling +[NewRelic startWithApplicationToken:];

    [NewRelic setApplicationVersion:(NSString*) appVersion];
Set a custom build identifier

As of version 5.1.0 of the New Relic iOS SDK, an API method allows you to set a custom build identifier that is displayed next to the application version in New Relic Mobile's Crash details page. Instead of using the CFBundleVersion string defined in Xcode with Objective-C, call the +[NewRelic setApplicationBuild:] method, and pass along the custom build identifier.

    [NewRelic setApplicationBuild:(NSString*) buildNumber];
Create custom metrics

Custom metrics can help track high level events specific to your application. With the recordMetric API, you can record arbitrary numerical data and named events with Objective-C and Swift. You can also use several API calls to record custom metrics that provide different levels of detail.

Objective-C: Send custom attributes and events to Insights

Use methods in the NewRelic object to send custom attributes and events to New Relic Insights. For details about the available methods for custom attributes and events with Objective-C, see the iOS SDK API reference.

Methods that return BOOL results return YES if they succeed, or NO if the operation did not complete. These methods are available in versions 5.0.0 or higher of the New Relic iOS SDK.

The SDK can store up to 64 user-defined attributes at a time. If you attempt to store more than 64 attributes, the SDK returns NO.

Custom attributes names should use the simplest format needed, and New Relic recommends single word attributes, containing no spaces. Attribute phrases can be formatted in camel case, so My Custom Attribute is better specified as myCustomAttribute. As with custom metrics:

  • Avoid using the characters / ] [ | * when naming things.
  • Avoid multi-byte characters.

Objective-C: Track custom network requests

If you can express a transactional network request in terms similar to an HTTP request, you can track it in New Relic Mobile. Use URLs that are well-formed and do not include highly variable paths or hostnames.

For requests that complete, use this method:

[NewRelic noticeNetworkRequestForURL:(NSURL*)url
                          httpMethod:(NSString*)httpMethod
                           withTimer:(NRTimer *)timer
                     responseHeaders:(NSDictionary *)headers
                          statusCode:(NSInteger)httpStatusCode
                           bytesSent:(NSUInteger)bytesSent
                       bytesReceived:(NSUInteger)bytesReceived
                        responseData:(NSData *)responseData
                           andParams:(NSDictionary *)params];

Parameters include:

Parameter Description
url The URL of the request
httpMethod The method type of the request; for example, POST, GET, etc.
timer An NRTimer that timed the network request
headers A dictionary containing the HTTP response headers, if available
httpStatusCode

The response status code

If the httpStatusCode is greater than or equal to 400, New Relic Mobile will record a server error and may capture the responseData body if provided.

bytesSent The size of the request body
bytesReceived The size of the responseBody
responseData The response body data, captured if New Relic Mobile records server error params
params Additional parameters included in an HTTP error metric if the HTTP transaction is an error

For requests that fail due to a socket or operating system error, use this method:

[NewRelic noticeNetworkFailureForURL:(NSURL *)url
                          httpMethod:(NSString*)httpMethod
                           withTimer:(NRTimer *)timer
                      andFailureCode:(NSInteger)iOSFailureCode];

Parameters include:

Parameter Description
url The URL of the request
httpMethod The method type of the request; for example, POST, GET, etc.
timer An NRTimer that timed the network request
iOSFailureCode

The failure code

Failure codes are interpreted as NSURLError* code. To view a complete list of the codes that New Relic Mobile supports, see NRConstants.h.

Instrument your Swift code

To have your own Swift code appear in interaction code breakdowns and timelines:

  • Add a startTracingMethod() call to the beginning of your method.
  • Add a endTracingMethodWithTimer() call to the end of it.
  • Always include an endTracingMethodWithTimer() call for each startTracingMethod() reference.
  • Include only one set of these commands in a given method.
    func myMethod(){
      	let timer = NRTimer();
      	NewRelic.startTracingMethod(#selector(MyClass.myMethod),
        		object: self,
        		timer: timer,
        		category: NRTraceTypeNone)
      	// … existing code
      	NewRelic.endTracingMethodWithTimer(timer)
      }

If you want your method’s performance to be included in the summary data on the APM Overview page, pass one of the NRTraceType enum values into the startTracingMethod() macro; for example:

NewRelic.startTracingMethod(#selector(MyClass.myMethod),
            object: self,
            timer: timer,
            category: NRTraceTypeDatabase)
Create and complete Swift interactions

By default, an interaction starts when a view controller is pushed. To manually start an interaction, use these API calls:

let uniqueIdentifier = NewRelic.startInteractionWithName("My Interaction");

This call will automatically begin tracking an interaction trace named My Interaction from the current line. It will also complete any previously running interaction. It returns a unique identifier that can be used to complete that interaction by using this API call:

NewRelic.stopCurrentInteraction(uniqueIdentifier)

This method will complete the interaction associated with the uniqueIdentifier if that interaction has not already completed automatically. You do not need to call this method.

Rename a default Swift interaction

By default, the iOS agent will start an interaction trace when a new view controller is displayed. The interactions are named using the format Display <ViewController>. To change these default names, implement the customNewRelicInteractionName() -> String method in your view controller, where the string returned becomes the interaction's name.

Set a custom application version with Swift

The New Relic iOS SDK allows you to set a custom application version string. Instead of using the string defined in CFBundleShortVersionString, call the NewRelic.setApplicationVersion() method, and pass along the custom application version before calling NewRelic.startWithApplicationToken();.

NewRelic.setApplicationVersion(String appVersion)
Set a custom build identifier with Swift

As of version 5.1.0 of the New Relic iOS SDK, an API method allows you to set a custom build identifier that is displayed next to the application version in New Relic Mobile's Crash details page. Instead of using the CFBundleVersion string defined in Xcode, call the NewRelic.setApplicationBuild() method, and pass along the custom build identifier.

    NewRelic.setApplicationBuild(buildNumber)
Create custom metrics with Swift

Custom metrics can help track high level events specific to your application. With the recordMetric API, you can record arbitrary numerical data and named events with Objective-C and Swift. You can also use several API calls to record custom metrics that provide different levels of detail.

Swift: Send custom attributes and events to Insights

Use methods in the NewRelic object to send custom attributes and events to New Relic Insights. For details about the available methods for custom attributes and events with Swift, see the iOS SDK API reference.

Methods that return BOOL results return YES if they succeed, or NO if the operation did not complete. These methods are available in versions 5.0.0 or higher of the New Relic iOS SDK.

The SDK can store up to 64 user-defined attributes at a time. If you attempt to store more than 64 attributes, the SDK returns NO.

Custom attributes names should use the simplest format needed, and New Relic recommends single word attributes, containing no spaces. Attribute phrases can be formatted in camel case, so My Custom Attribute is better specified as myCustomAttribute. As with custom metrics:

  • Avoid using the characters / ] [ | * when naming things.
  • Avoid multi-byte characters.

Swift: Track custom network requests

If you can express a transactional network request in terms similar to an HTTP request, you can track it in New Relic Mobile. Use URLs that are well-formed and do not include highly variable paths or hostnames.

For requests that complete, use this method:

NewRelic.noticeNetworkRequestForURL(url: NSURL!,
			httpMethod: String!,
    			withTimer: NRTimer!,
    			responseHeaders:[NSObject : AnyObject]!,
    			statusCode: Int,
    			bytesSent: UInt,
    			bytesReceived: UInt,
    			responseData: NSData!,
    			andParams: [NSObject : AnyObject]!)

Parameters include:

Parameter Description
url

The URL of the request

httpMethod The method type of the request; for example, POST, GET, etc.
timer An NRTimer that timed the network request
headers A dictionary containing the HTTP response headers, if available
httpStatusCode

The response status code

If the httpStatusCode is greater than or equal to 400, New Relic Mobile will record a server error and may capture the responseData body if provided.

bytesSent The size of the request body
bytesReceived The size of the responseBody
responseData The response body data, captured if New Relic Mobile records Server error params
params Additional parameters included in an HTTP error metric if the HTTP transaction is an error

For requests that fail due to a socket or operating system error, use this method:

NewRelic.noticeNetworkFailureForURL(url: NSURL!,
				httpMethod: NSString!,
				withTimer: NRTimer!,
				andFailureCode: Int)

Parameters include:

Parameter Description
url The URL of the request
httpMethod The method type of the request; for example, POST, GET, etc.
timer An NRTimer that timed the network request

iOSFailureCode

The failure code

Failure codes are interpreted as NSURLError* code. To view a complete list of the codes that New Relic Mobile supports, see NRConstants.h.

For more help

Recommendations for learning more: