Developers
The Apple SDK is designed to support both iOS and tvOS devices.
To send data from your iOS app to your mParticle workspace input, you need an API key and secret. In the mParticle dashboard, navigate to Setup > Inputs and select the iOS (or tvOS) platform. From here you will be able to create a key and secret. Reference the guide section for information on creating inputs.
mParticle’s iOS SDK is powered by a “core” library, which supports mParticle’s server-side integrations and audience platform. Please follow the releases page on Github to stay up to date with the latest version.
You can add the SDK via CocoaPods, Carthage, or by building manually from source.
To integrate the SDK using CocoaPods, specify it in your Podfile:
use_frameworks!
target '<Your Target>' do
pod 'mParticle-Apple-SDK', '~> 7.8'
end
To integrate the SDK using Carthage, specify it in your Cartfile:
github "mparticle/mparticle-apple-sdk" ~> 7.8
You can also manually include the latest binary distribution or build the SDK from source.
You can initialize the SDK with an MParticleOptions
object. At minimum you must supply your mParticle workspace key and secret.
Supply your MParticleOptions
object to the mParticle start
API to initialize the SDK:
The SDK is designed to be initialized within the application:didFinishLaunchingWithOptions:
method. The SDK performs very little work before delegating all actions to a background queue. Also, please do not use Grand Central Dispatch’s dispatch_async
API to start the SDK. If the SDK is initialized later in the UIApplication lifecycle, session and installation events may not be recorded correctly.
// Assumes the SDK has been included as a dynamic library
// Requires "Enable Modules (C and Objective-C)" in pbxproj
@import mParticle_Apple_SDK;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//initialize mParticle
MParticleOptions *options = [MParticleOptions optionsWithKey:@"REPLACE WITH APP KEY"
secret:@"REPLACE WITH APP SECRET"];
[[MParticle sharedInstance] startWithOptions:options];
return YES;
}
import mParticle_Apple_SDK
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//initialize mParticle
let options = MParticleOptions(key: "REPLACE WITH APP KEY",
secret: "REPLACE WITH APP SECRET")
MParticle.sharedInstance().start(with: options)
return true
}
Install and open a test build of your app on a device or simulator. Your app should immediately begin uploading installation and session data and you’ll see that data arriving in the live stream almost immediately:
If you don’t see data in the live stream, check that you’ve correctly copied your API key and secret, and look in the Xcode log console for any errors logged by the mParticle SDK. Reference the guide section for more information on the live stream.
Several integrations require additional client-side add-on libraries called “kits.” Some kits embed other SDKs, others just contain a bit of additional functionality. Kits are designed to feel just like server-side integrations; you enable, disable, filter, sample, and otherwise tweak kits completely from the mParticle platform UI. Reference the kit documentation for information on kits.
The SDK will automatically initialize with the most recent user identities from the most recently active user. You may override this by including an identity request via the identify
API of your MParticleOptions
object:
MParticleOptions *options = [MParticleOptions optionsWithKey:@"REPLACE WITH APP KEY"
secret:@"REPLACE WITH APP SECRET"];
options.identifyRequest = identityRequest;
[[MParticle sharedInstance] startWithOptions:options];
let options = MParticleOptions(key: "REPLACE WITH APP KEY",
secret: "REPLACE WITH APP SECRET")
options.identifyRequest = identityRequest
MParticle.sharedInstance().start(with: options)
See the IDSync documentation for more information on building a complete identity request.
All data sent into an mParticle input must be marked as either “development” or “production”. The SDK attempts to detect the environment by reading the provisioning profile at runtime.
In addition to uploading data as development, the SDK will also adjust some of its functionality to allow for a faster integration process:
NSAssert
exceptions when invalid objects are passed to its APIs, such as the IDSync and commerce APIs.You can override the environment in your MParticleOptions
object:
MParticleOptions *options = [MParticleOptions optionsWithKey:@"REPLACE WITH APP KEY"
secret:@"REPLACE WITH APP SECRET"];
options.environment = MPEnvironmentProduction;
[[MParticle sharedInstance] startWithOptions:options];
let options = MParticleOptions(key: "REPLACE WITH APP KEY",
secret: "REPLACE WITH APP SECRET")
options.environment = MPEnvironment.production;
MParticle.sharedInstance().start(with: options)
All development data will appear in your workspace’s live stream. In order to see production data, log into the mParticle platform, navigate to live stream, select your app, and filter on the appropriate devices based on IDFA.
Data Master allows you to define the format of any data being sent to the mParticle SDK. After creating a data plan in the mParticle UI, you simply set the data plan ID in the MParticleOptions
object along with the optional data plan version and initialize the SDK as normal. When you return to the mParticle UI and visit the Live Stream section to view incoming data, you’ll find warnings for any data that has been recieved that does not conform to your data plan.
MParticleOptions *options = [MParticleOptions optionsWithKey:@"REPLACE WITH APP KEY"
secret:@"REPLACE WITH APP SECRET"];
options.dataPlanId = @"mobile_data_plan"; // Always undercase with white space replaced with '_'
options.dataPlanVersion = @(1);
let options = MParticleOptions(key: "REPLACE WITH APP KEY",
secret: "REPLACE WITH APP SECRET")
options.dataPlanId = "mobile_data_plan" // Always undercase with white space replaced with '_'
options.dataPlanVersion = @(1)
The mParticle Apple SDK will not log any messages to the console by default, but you can set a log level between verbose and error to allow corresponding messages to be written out using NSLog. However, you should ensure the log level is only set for your development or Ad-Hoc builds and that the log level remains set to MPILogLevelNone (the default) in your production App Store apps. This is important to avoid leaking information and can be done with preprocessor directives or otherwise depending on your app’s configuration.
MParticleOptions *options = [MParticleOptions optionsWithKey:@"REPLACE WITH APP KEY"
secret:@"REPLACE WITH APP SECRET"];
options.logLevel = MPILogLevelVerbose;
[[MParticle sharedInstance] startWithOptions:options];
let options = MParticleOptions(key: "REPLACE WITH APP KEY",
secret: "REPLACE WITH APP SECRET")
options.logLevel = MPILogLevel.verbose
MParticle.sharedInstance().start(with: options)
You can also set a custom logger block to be used in case you want to send the logs out to a remote server or do any other custom handling of the messages.
Note that if you set a custom log handler, the SDK will only use that and will not log to the system log, but if you want the messages to show up in both places you can do so by simply calling NSLog within the log callback block.
We strongly recommend you avoid inspecting the logs programmatically to determine SDK behavior unless it’s 100% necessary for a temporary workaround—log messages are not guaranteed to be consistent between releases.
MParticleOptions *options = [MParticleOptions optionsWithKey:@"REPLACE WITH APP KEY"
secret:@"REPLACE WITH APP SECRET"];
options.customLogger = ^(NSString *message) {
// handle log message
};
[[MParticle sharedInstance] startWithOptions:options];
let options = MParticleOptions(key: "REPLACE WITH APP KEY",
secret: "REPLACE WITH APP SECRET")
options.customLogger = { (message: String) in
// handle log message
}
MParticle.sharedInstance().start(with: options)
By default the mParticle SDK replaces your UIApplication.delgate
with its own NSProxy
implementation in order to facilitate and simplify the handling of remote notifications, local notifications, interactions with notification actions, and application launching. Over time we have found this to be less intrusive than other SDKs which instead perform swizzling.
You can choose to disable this via the proxyAppDelegate
flag of the MParticleOptions
object. Doing so means you will need to audit any kits that you use invididually to determine which UIApplication
APIs they require. Any required methods should be manually invoked on mParticle, such that mParticle can forward those APIs onto each kit.
MParticleOptions *options = [MParticleOptions optionsWithKey:@"REPLACE WITH APP KEY"
secret:@"REPLACE WITH APP SECRET"];
options.proxyAppDelegate = NO;
[[MParticle sharedInstance] startWithOptions:options];
let options = MParticleOptions(key: "REPLACE WITH APP KEY",
secret: "REPLACE WITH APP SECRET")
options.proxyAppDelegate = false
MParticle.sharedInstance().start(with: options)
Here’s an example of how you can manually pass the application:continueUserActivity:restorationHandler:
API to mParticle:
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> *restorableObjects))restorationHandler {
[[MParticle sharedInstance] continueUserActivity: userActivity
restorationHandler: restorationHandler];
return YES;
}
func application(_ application: UIApplication, continue userActivity: NSUserActivity,
restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
MParticle.sharedInstance().continue(userActivity) { (restorableObjects: [Any]?) in
restorationHandler(restorableObjects as? [UIUserActivityRestoring])
}
return true
}
The following is a list of all calls that would need to be made to the mParticle SDK from your app delegate:
// Required for universal links and all kits such as AppsFlyer, Braze, and Branch
- (BOOL)continueUserActivity:(nonnull NSUserActivity *)userActivity restorationHandler:(void(^ _Nonnull)(NSArray * _Nullable restorableObjects))restorationHandler;
// Required if supporting custom URL schemes
- (void)openURL:(NSURL *)url options:(nullable NSDictionary *)options;
// Only required if supporting iOS 9 or below
- (void)openURL:(NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(nullable id)annotation;
// Required for all kits that have remote or local notification functionality
// Also required if using mParticle to register for push notification without any kits
- (void)didReceiveLocalNotification:(UILocalNotification *)notification;
- (void)didReceiveRemoteNotification:(NSDictionary *)userInfo;
- (void)didFailToRegisterForRemoteNotificationsWithError:(nullable NSError *)error;
- (void)didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken;
- (void)handleActionWithIdentifier:(nullable NSString *)identifier forLocalNotification:(nullable UILocalNotification *)notification;
- (void)handleActionWithIdentifier:(nullable NSString *)identifier forRemoteNotification:(nullable NSDictionary *)userInfo;
By default the SDK automatically collects http user agent information on initialization. This information is required by some of mParticle’s server-side Attribution partners for accurate fingerprinting of a device. mParticle needs to open a UIWebView
instance to collect this data, which may require additional memory overhead on app startup. If you would prefer to set the user agent yourself, or not to collect it at all, you can turn off this default behavior in MParticleOptions
.
MParticleOptions *options = [MParticleOptions optionsWithKey:@"REPLACE WITH APP KEY"
secret:@"REPLACE WITH APP SECRET"];
options.collectUserAgent = NO;
options.customUserAgent = @"Mozilla/5.0 (iPhone; CPU iPhone OS %@ like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Mobile/xxxx mParticle/xxxx";
[[MParticle sharedInstance] startWithOptions:options];
let options = MParticleOptions(key: "REPLACE WITH APP KEY",
secret: "REPLACE WITH APP SECRET")
options.collectUserAgent = false
options.customUserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS %@ like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Mobile/xxxx mParticle/xxxx"
MParticle.sharedInstance().start(with: options)
To save bandwidth and device battery, mParticle does not upload each event as it is recorded. Instead, events are assembled into batches and uploaded based on specific triggers. When a trigger is fired, the SDK will:
The following will trigger SDK batch creation and upload:
upload
API is invoked (see below)You can configure the regular upload trigger:
MParticleOptions *options = [MParticleOptions optionsWithKey:@"REPLACE WITH APP KEY"
secret:@"REPLACE WITH APP SECRET"];
options.uploadInterval = 60;
[[MParticle sharedInstance] startWithOptions:options];
let options = MParticleOptions(key: "REPLACE WITH APP KEY",
secret: "REPLACE WITH APP SECRET")
options.uploadInterval = 60;
MParticle.sharedInstance().start(with: options)
You can also force an upload trigger with the upload
method:
[[MParticle sharedInstance] upload];
MParticle.sharedInstance().upload()
You can read detailed instructions for implementing crash reporting in the error tracking documentation under crash reporting.
If your app targets iOS and tvOS in the same Xcode project, you need to configure the Podfile
differently in order to use the SDK with multiple platforms. You can find an example of multi-platform configuration here.
Was this page helpful?