Initialize the SDK

The mParticle SDK is initialized by calling the startWithOptions method within the application:didFinishLaunchingWithOptions: delegate call. Preferably, the initialization method call should be one of the last statements in application:didFinishLaunchingWithOptions:. The startWithOptions method requires an options argument containing your key and secret and an initial Identity request.

Note that it is imperative for the SDK to be initialized in the application:didFinishLaunchingWithOptions: method. Other parts of the SDK rely on the UIApplicationDidBecomeActiveNotification notification to function properly. Failing to start the SDK as indicated will impair it. Also, please do not use GCD’s dispatch_async to start the SDK.

1. Import the SDK

For apps supporting iOS 8 and above, Apple recommends using the import syntax for modules or semantic import. However, if you prefer the traditional CocoaPods and static libraries delivery mechanism, that is fully supported as well.

// If using mParticle as a framework:
@import mParticle_Apple_SDK; //Apple recommended syntax, but requires "Enable Modules (C and Objective-C)" in pbxproj
// OR
#import <mParticle_Apple_SDK/mParticle.h> //Works when modules are not enabled

// If not using use_frameworks!
#import <mParticle-Apple-SDK/mParticle.h>
// OR
#import "mParticle.h"
import mParticle_Apple_SDK

2. Create an MParticleOptions object and start the SDK

You can initialize the SDK with an MParticleOptions object. At minimum, you must supply your mParticle workspace key and secret.

Pass your MParticleOptions object to the mParticle startWithOptions API to initialize the SDK.

MParticleOptions *mParticleOptions = [MParticleOptions optionsWithKey:@"REPLACE ME"
                                                               secret:@"REPLACE ME"];
//Please see the Identity page for more information on building this object
MPIdentityApiRequest *request = [MPIdentityApiRequest requestWithEmptyUser];
request.email = @"email@example.com";
mParticleOptions.identifyRequest = request;
mParticleOptions.onIdentifyComplete = ^(MPIdentityApiResult * _Nullable apiResult, NSError * _Nullable error) {
    NSLog(@"Identify complete. userId = %@ error = %@", apiResult.user.userId, error);
};

[[MParticle sharedInstance] startWithOptions:mParticleOptions];
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
       // Override point for customization after application launch.
        let mParticleOptions = MParticleOptions(key: "<<<App Key Here>>>", secret: "<<<App Secret Here>>>")
        
       //Please see the Identity page for more information on building this object
        let request = MPIdentityApiRequest()
        request.email = "email@example.com"
        mParticleOptions.identifyRequest = request
        mParticleOptions.onIdentifyComplete = { (apiResult, error) in
            NSLog("Identify complete. userId = %@ error = %@", apiResult?.user.userId.stringValue ?? "Null User ID", error?.localizedDescription ?? "No Error Available")
        }
        
       //Start the SDK
        MParticle.sharedInstance().start(with: mParticleOptions)
        
       return true
    }

Please see Identity for more information on supplying an MPIdentityApiRequest object during SDK initialization.

Development and Production Environments

The iOS SDK will detect whether your app is running in a development environment or a production environment. Alternatively, you can set an environment manually. In development mode the SDK will print informative log messages and will upload data at a much higher rate to mParticle servers to allow for easier debugging.

In order to see the stream of events sent from your app to mParticle servers, log into the mParticle platform, navigate to Live Stream, select your app, and filter on the appropriate devices.

//The iOS SDK will detect Development mode if the app is connected to the Xcode debugger
//or has an Adhoc or Development provisioning profile
MParticleOptions *options = [[MParticleOptions alloc] init];
    options.apiKey = @"foo";
    options.apiSecret = @"bar";
    options.environment = MPEnvironmentProduction;
    options.installType = MPInstallationTypeKnownUpgrade;
    [[MParticle sharedInstance] startWithOptions:options];
Environment Description
Auto-Detect Default. The SDK will detect environment automatically.
Development The running environment of the SDK is development
Production The running environment of the SDK is production

Console Logging

During development, set the logLevel property to control the verbosity of the mParticle SDK’s console output. For App Store-provisioned builds, this property will be ignored, and MPILogLevelNone will be used.

[mParticle sharedInstance].logLevel = MPILogLevelDebug;

User Agent Collection

By default the SDK automatically collects http user agent information on initialize. 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 behaviour in MParticleOptions.

MParticleOptions *options = [[MParticleOptions alloc] init];
    // See above for other required settings
    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"

AppDelegate Proxy

By default the mParticle SDK uses NSProxy to seamlessly integrate with the application’s app delegate in order to facilitate and simplify the handling of remote notifications, local notifications, interactions with notification actions, and application launching. This feature allows for a lot of needed work to be done automatically on your behalf, and does not interfere in any way with the functioning of your app.

You can choose to disable this feature by passing NO to proxyAppDelegate: in the start method of the SDK. However, by doing so you will need to code the calls to the mParticle SDK when the app is launched, a remote or local notification is received, and the user interacts with a notification action.

MParticleOptions *options = [[MParticleOptions alloc] init];
    options.apiKey = @"foo";
    options.apiSecret = @"bar";
    options.proxyAppDelegate = NO;
    [[MParticle sharedInstance] startWithOptions:options];
let mParticleOptions = MParticleOptions(key: "<<<App Key Here>>>", secret: "<<<App Secret Here>>>")
mParticleOptions.proxyAppDelegate = false
MParticle.sharedInstance().start(with: mParticleOptions)

The following is a list of all calls that would need to be made to the mParticle SDK from your app delegate:

- (void)application:(UIApplication *)application
        didReceiveLocalNotification:(UILocalNotification *)notification
{
    [[MParticle sharedInstance] didReceiveLocalNotification:notification];
}

- (void)application:(UIApplication *)application
        didReceiveRemoteNotification:(NSDictionary *)userInfo
        fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    [[MParticle sharedInstance] didReceiveRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application
        didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [[MParticle sharedInstance] didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application
        didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    [[MParticle sharedInstance] didFailToRegisterForRemoteNotificationsWithError:error];
}

- (void)application:(UIApplication *)application
        handleActionWithIdentifier:(NSString *)identifier
        forLocalNotification:(UILocalNotification *)notification
        completionHandler:(void (^)())completionHandler
{
    [[MParticle sharedInstance] handleActionWithIdentifier:identifier
                                      forLocalNotification:notification];
}

- (void)application:(UIApplication *)application
        handleActionWithIdentifier:(NSString *)identifier
        forRemoteNotification:(NSDictionary *)userInfo
        completionHandler:(void (^)())completionHandler
{
    [[MParticle sharedInstance] handleActionWithIdentifier:identifier
                                     forRemoteNotification:userInfo];
}

// iOS and tvOS
- (BOOL)application:(UIApplication *)application
        openURL:(NSURL *)url
        sourceApplication:(NSString *)sourceApplication
        annotation:(id)annotation
{
    [[MParticle sharedInstance] openURL:url
                      sourceApplication:sourceApplication
                             annotation:annotation];
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    MParticle.sharedInstance().didRegisterForRemoteNotifications(withDeviceToken: deviceToken)
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    MParticle.sharedInstance().didFailToRegisterForRemoteNotificationsWithError(error)
}

// iOS and tvOS
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    MParticle.sharedInstance().open(url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String, annotation: options[UIApplicationOpenURLOptionsKey.annotation])
}


//The UIApplicationDelegate proxy cannot intercept invocations from the UNUserNotificationCenterDelegate introduced in iOS 10. If you use this delegate’s willPresentNotification or didReceiveNotificationResponse, you will need to call the equivalent method in the mParticle SDK as shown below:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    MParticle.sharedInstance().userNotificationCenter(center, willPresent: notification)

}

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    MParticle.sharedInstance().userNotificationCenter(center, didReceive: response)
}