Git Product home page Git Product logo

react-native-mparticle's Introduction

react-native-mparticle

npm version Standard - JavaScript Style Guide

React Native allows developers to use a single code base to deploy features to multiple platforms. With the mParticle React Native library, you can leverage a single API to deploy your data to hundreds of integrations from your iOS and Android apps.

Supported Features

Method Android iOS
Custom Events
  • Page Views
  • Identity
  • eCommerce
  • Consent
  • Installation

    Download and install the mParticle React Native library from npm:

    $ npm install react-native-mparticle --save

    iOS

    1. Copy your mParticle key and secret from your app's dashboard.
    1. Install the SDK using CocoaPods:

    The npm install step above will automatically include our react framework and the core iOS framework in your project. However depending on your app and its other dependecies you must integrate it in 1 of 3 ways

    A. Static Libraries are the React Native default but since mParticle iOS contains swift code you need to add an exception for it in the from of a pre-install command in the Podfile.

    pre_install do |installer|
      installer.pod_targets.each do |pod|
        if pod.name == 'mParticle-Apple-SDK'
          def pod.build_type;
            Pod::BuildType.new(:linkage => :dynamic, :packaging => :framework)
          end
        end
      end
    end

    Then run the following command

    bundle exec pod install
    

    B&C. Frameworks are the default for Swift development and while it isn't preferred by React Native it is supported. Additionally you can define whether the frameworks are built staticly or dynamically.

    Update your Podfile to be ready to use dynamically linked frameworks by commenting out the following line

    # :flipper_configuration => flipper_config,

    Then run either of the following commands

    $ USE_FRAMEWORKS=static bundle exec pod install
    

    or

    $ USE_FRAMEWORKS=dynamic bundle exec pod install
    
    1. Import and start the mParticle Apple SDK into Swift or Objective-C.

    The mParticle SDK is initialized by calling the startWithOptions method within the application:didFinishLaunchingWithOptions: delegate call.

    Preferably the location of the initialization method call should be one of the last statements in the application:didFinishLaunchingWithOptions:.

    The startWithOptions method requires an options argument containing your key and secret and an initial Identity request.

    Note that you must initialize the SDK 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.

    For more help, see the iOS set up docs.

    Swift Example

    import mParticle_Apple_SDK
    
    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>>>")
            
            //optional- Please see the Identity page for more information on building this object
            let request = MPIdentityApiRequest()
            request.email = "[email protected]"
            mParticleOptions.identifyRequest = request
            //optional
            mParticleOptions.onIdentifyComplete = { (apiResult, error) in
                NSLog("Identify complete. userId = %@ error = %@", apiResult?.user.userId.stringValue ?? "Null User ID", error?.localizedDescription ?? "No Error Available")
            }
            //optional
            mParticleOptions.onAttributionComplete = { (attributionResult, error) in
                        NSLog(@"Attribution Complete. attributionResults = %@", attributionResult.linkInfo)
            }
            MParticle.sharedInstance().start(with: mParticleOptions)        
            return true
    }

    Objective-C Example

    Your import statement should be this:

    #if defined(__has_include) && __has_include(<mParticle_Apple_SDK/mParticle.h>)
        #import <mParticle_Apple_SDK/mParticle.h>
    #elif defined(__has_include) && __has_include(<mParticle_Apple_SDK_NoLocation/mParticle.h>)
        #import <mParticle_Apple_SDK_NoLocation/mParticle.h>
    #else
        #import "mParticle.h"
    #endif

    Next, you'll need to start the SDK:

    - (BOOL)application:(UIApplication *)application
            didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
        MParticleOptions *mParticleOptions = [MParticleOptions optionsWithKey:@"REPLACE ME"
                                                                       secret:@"REPLACE ME"];
        
        //optional - Please see the Identity page for more information on building this object
        MPIdentityApiRequest *request = [MPIdentityApiRequest requestWithEmptyUser];
        request.email = @"[email protected]";
        mParticleOptions.identifyRequest = request;
        //optional
        mParticleOptions.onIdentifyComplete = ^(MPIdentityApiResult * _Nullable apiResult, NSError * _Nullable error) {
            NSLog(@"Identify complete. userId = %@ error = %@", apiResult.user.userId, error);
        };
        //optional
        mParticleOptions.onAttributionComplete(MPAttributionResult * _Nullable attributionResult, NSError * _Nullable error) {
            NSLog(@"Attribution Complete. attributionResults = %@", attributionResult.linkInfo)
        }
        
        [[MParticle sharedInstance] startWithOptions:mParticleOptions];
        
        return YES;
    }

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

    1. Remember to start Metro with:
    $ npm start

    and build your workspace from xCode.

    Android

    1. Copy your mParticle key and secret from your workspace's dashboard and construct an MParticleOptions object.

    2. Call start from the onCreate method of your app's Application class. It's crucial that the SDK be started here for proper session management. If you don't already have an Application class, create it and then specify its fully-qualified name in the <application> tag of your app's AndroidManifest.xml.

    For more help, see the Android set up docs.

    package com.example.myapp;
    
    import android.app.Application;
    import com.mparticle.MParticle;
    
    class MyApplication : Application() {
        fun onCreate() {
            super.onCreate()
            val options: MParticleOptions = MParticleOptions.builder(this)
                .credentials("REPLACE ME WITH KEY", "REPLACE ME WITH SECRET")
                //optional
                .logLevel(MParticle.LogLevel.VERBOSE)
                //optional
                .identify(identifyRequest)
                //optional
                .identifyTask(
                    BaseIdentityTask()
                        .addFailureListener { errorResponse -> }
                        .addSuccessListener{ result -> }
                )
                //optional
                .attributionListener(this)
                .build()
            MParticle.start(options)
        }
    }

    Warning: Don't log events in your Application.onCreate(). Android may instantiate your Application class in the background without your knowledge, including when the user isn't using their device, and lead to unexpected results.

    Usage

    Import the mParticle Module

    import MParticle from 'react-native-mparticle'

    Logging Events

    To log basic events:

    MParticle.logEvent('Test event', MParticle.EventType.Other, { 'Test key': 'Test value' })

    To log commerce events:

    const product = new MParticle.Product('Test product for cart', '1234', 19.99)
    const transactionAttributes = new MParticle.TransactionAttributes('Test transaction id')
    const event = MParticle.CommerceEvent.createProductActionEvent(MParticle.ProductActionType.AddToCart, [product], transactionAttributes)
    
    MParticle.logCommerceEvent(event)
    const promotion = new MParticle.Promotion('Test promotion id', 'Test promotion name', 'Test creative', 'Test position')
    const event = MParticle.CommerceEvent.createPromotionEvent(MParticle.PromotionActionType.View, [promotion])
    
    MParticle.logCommerceEvent(event)
    const product = new MParticle.Product('Test product that was viewed', '5678', 29.99)
    const impression = new MParticle.Impression('Test impression list name', [product])
    const event = MParticle.CommerceEvent.createImpressionEvent([impression])
    
    MParticle.logCommerceEvent(event)

    To log screen events:

    MParticle.logScreenEvent('Test screen', { 'Test key': 'Test value' })

    User

    To set, remove, and get user details, call the User or Identity methods as follows:

    MParticle.User.setUserAttribute('User ID', 'Test key', 'Test value')
    MParticle.User.setUserAttribute('User ID', MParticle.UserAttributeType.FirstName, 'Test first name')
    MParticle.User.setUserAttributeArray('User ID', 'Test key', ['Test value 1', 'Test value 2'])
    MParticle.User.setUserTag('User ID', 'Test value')
    MParticle.User.removeUserAttribute('User ID', 'Test key')
    MParticle.Identity.getUserIdentities((userIdentities) => {
    	console.debug(userIdentities);
    });

    IdentityRequest

    var request = new MParticle.IdentityRequest()

    Setting user identities:

    var request = new MParticle.IdentityRequest();
    request.setUserIdentity('[email protected]', MParticle.UserIdentityType.Email);

    Identity

    MParticle.Identity.getCurrentUser((currentUser) => {
        console.debug(currentUser.userID);
    });
    var request = new MParticle.IdentityRequest();
    
    MParticle.Identity.identify(request, (error, userId) => {
        if (error) {
            console.debug(error); //error is an MParticleError
        } else {
            console.debug(userId);
        }
    });
    var request = new MParticle.IdentityRequest();
    request.email = 'test email';
    
    MParticle.Identity.login(request, (error, userId) => {
        if (error) {
            console.debug(error); //error is an MParticleError
        } else {
            console.debug(userId);
        }
    });
    var request = new MParticle.IdentityRequest();
    
    MParticle.Identity.logout(request, (error, userId) => {
        if (error) {
            console.debug(error);
        } else {
            console.debug(userId);
        }
    });
    var request = new MParticle.IdentityRequest();
    request.email = 'test email 2';
    
    MParticle.Identity.modify(request, (error, userId) => {
        if (error) {
            console.debug(error); //error is an MParticleError
        } else {
            console.debug(userId);
        }
    });

    Attribution

    var attributions = MParticle.getAttributions();
    

    In order to listen for Attributions asynchronously, you need to set the proper field in MParticleOptions as shown in the Android or the iOS SDK start examples.

    Kits

    Check if a kit is active

    var isKitActive = MParticle.isKitActive(kitId);
    

    Check and set the SDK's opt out status

    var isOptedOut = MParticle.getOptOut();
    MParticle.setOptOut(!isOptedOut);
    

    Push Registration

    The method MParticle.logPushRegistration() accepts 2 parameters. For Android, provide both the pushToken and senderId. For iOS, provide the push token in the first parameter, and simply pass null for the second parameter.

    Android

    MParticle.logPushRegistration(pushToken, senderId);
    

    iOS

    MParticle.logPushRegistration(pushToken, null);
    

    GDPR Consent

    Add a GDPRConsent

    var gdprConsent = GDPRConsent()
        .setConsented(true)
        .setDocument("the document")
        .setTimestamp(new Date().getTime())  // optional, native SDK will automatically set current timestamp if omitted
        .setLocation("the location")
        .setHardwareId("the hardwareId");
    
    MParticle.addGDPRConsentState(gdprConsent, "the purpose");
    

    Remove a GDPRConsent

    MParticle.removeGDPRConsentStateWithPurpose("the purpose");
    

    CCPA Consent

    Add a CCPAConsent

    var ccpaConsent = CCPAConsent()
        .setConsented(true)
        .setDocument("the document")
        .setTimestamp(new Date().getTime())  // optional, native SDK will automatically set current timestamp if omitted
        .setLocation("the location")
        .setHardwareId("the hardwareId");
    
    MParticle.addCCPAConsentState(ccpaConsent);
    

    Remove CCPAConsent

    MParticle.removeCCPAConsentState();
    

    License

    Apache 2.0

    react-native-mparticle's People

    Contributors

    ajiljagadeesh7 avatar alexs-mparticle avatar alla-uday avatar altaywtf avatar apstone avatar brandonstalnaker avatar dependabot[bot] avatar donovangallaway avatar felipecoro avatar jpavioli avatar klippx avatar matthewincledon avatar mchuangatmp avatar mmustafa-tse avatar ngregory-rbi avatar peterjenkins avatar rmi22186 avatar saleksandras avatar samdozor avatar shwangmp avatar willpassidomo avatar

    Stargazers

     avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

    Watchers

     avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

    react-native-mparticle's Issues

    fatal error: 'mParticle.h' file not found

    HI! After installing the SDK and installing the RN package and linking it, the file

    node_modules/react-native-mparticle/ios/RNMParticle/RNMParticle.m:2:9: fatal error: 'mParticle.h' file not found

    the RNMParticle.h file can't find the import "mParticle.h"

    #import "mParticle.h"
    I tried also #import <mParticle_Apple_SDK/mParticle.h>

    and didn't work,

    Any suggestion will be appreciated,
    Thanks

    Feature Request: Raise an event once at attribution is fetched at the native layers.

    Not rocket science here, I suspect this is only not already done as a matter of time/resources! Hoping this request may help.

    At the moment the react-native-mparticle only has a method to synchronously get attributions from the likes of Branch, Adjust , etc. This is obviously tricky as on one hand we don't want to call this too early, as in that case there will be no attribution to fetch and it will ultimately not be logged when/if it does arrive. However if we put this call later on in our onboarding flow, the user may quit the app before the attribution is recorded.

    In order to be able to log the attribution as soon as it is available, it would be great to have the onAttributionComplete callbacks at the native layer raise an event on the JS layer, that we can subscribe to, and deliver the necessary payload with attribution data.

    Environment setup?

    Is it possible to setup to diff environments like in the Node SDK.

    var batch = new mParticle.Batch(mParticle.Batch.Environment.development);

    I've search in the entire lib and found nothing related to environments.

    logEvent calls crash because of update in mparticle-android-sdk

    The dependency on the android SDK is currently set to com.mparticle:android-core:[5.9.3, ).

    Version 5.10.2 of that SDK was just released on 10/7, and includes (apparently) breaking changes to (at least) the logEvent method (see: mParticle/mparticle-android-sdk@74a34d7#diff-402a8f1a5d5e1043d9b3f6c5b83af0c5, lines 346-394)

    Any fresh builds using this plugin will crash if you try to log an event.

    Sample stacktrace:

    2019-10-08 16:20:57.182 20665-20975/[my redacted package name] E/unknown:ReactNative: Exception in native call
        java.lang.RuntimeException: Could not invoke MParticle.logEvent
            at com.facebook.react.bridge.JavaMethodWrapper.invoke(JavaMethodWrapper.java:383)
            at com.facebook.react.bridge.JavaModuleWrapper.invoke(JavaModuleWrapper.java:158)
            at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)
            at android.os.Handler.handleCallback(Handler.java:751)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:29)
            at android.os.Looper.loop(Looper.java:154)
            at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:232)
            at java.lang.Thread.run(Thread.java:762)
         Caused by: java.lang.reflect.InvocationTargetException
            at java.lang.reflect.Method.invoke(Native Method)
            at com.facebook.react.bridge.JavaMethodWrapper.invoke(JavaMethodWrapper.java:372)
            at com.facebook.react.bridge.JavaModuleWrapper.invoke(JavaModuleWrapper.java:158) 
            at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method) 
            at android.os.Handler.handleCallback(Handler.java:751) 
            at android.os.Handler.dispatchMessage(Handler.java:95) 
            at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:29) 
            at android.os.Looper.loop(Looper.java:154) 
            at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:232) 
            at java.lang.Thread.run(Thread.java:762) 
         Caused by: java.lang.NoSuchMethodError: No virtual method logEvent(Lcom/mparticle/BaseEvent;)V in class Lcom/mparticle/MParticle; or its super classes (declaration of 'com.mparticle.MParticle' appears in /data/app/[my redacted package name]-2/base.apk:classes5.dex)
            at com.mparticle.react.MParticleModule.logEvent(MParticleModule.java:62)
            at java.lang.reflect.Method.invoke(Native Method) 
            at com.facebook.react.bridge.JavaMethodWrapper.invoke(JavaMethodWrapper.java:372) 
            at com.facebook.react.bridge.JavaModuleWrapper.invoke(JavaModuleWrapper.java:158) 
            at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method) 
            at android.os.Handler.handleCallback(Handler.java:751) 
            at android.os.Handler.dispatchMessage(Handler.java:95) 
            at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:29) 
            at android.os.Looper.loop(Looper.java:154) 
            at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:232) 
            at java.lang.Thread.run(Thread.java:762)
    

    Can you please change the dependencies to use static, pinned versions instead of open-ended dynamic versions?

    setUserAttributeArray does not work on iOS

    setUserAttributeArray(userId, key, values) does not work on iOS. However, it works on Android and Web. I debugged this using the livestream feature and noticed there is not even an event reaching the mParticle server so the problem was clearly isolated to the react native implementation.

    I looked through the source and noticed that it delegates to instance of MParticleUser but sending the message setUserAttribute which does not accept NSArray for value:

    - (void)setUserAttribute:(nonnull NSString *)key value:(nonnull id)value {
    

    Rather, it should probably be using this method:

    - (void)setUserAttributeList:(nonnull NSString *)key values:(nonnull NSArray<NSString *> *)values {
    

    I made a fork and made the changes, and tried this out locally. And it worked wonders 👍

    Question: Is autolinking supported?

    Does this react native library support Autolinking? or do we have to really manually link the library? Autolinking seems to be the way to go nowadays since React Native 0.60. Also, if not is there a plan to support autolinking?

    The current installation documents specifically say to use react-native link.

    If this still is this case this should be npx react-native link react-native-mparticle to isolate linking to that specific library.

    Documentation needs more clarity around identification

    The react native documentation is lacking detail around identification that makes it confusing. Here's what I've run into so far:

    • Do we need to set up identification in the native code in order to use the SDK? It says it's optional, but also says here that we need to set up identity requests in the native code first.
    • Before a user has identifying information available, what should we be using to identify them? IDFA? Are they automatically identified through the IDFA when an identity request is created, as specified in the iOS docs? I see that there could be a lot of flexibility in how to do this, but I really would like to be shown the "recommended way" to handle it.
    • Does the comment about IDFA's no longer being included automatically need to be handled somehow? Not sure how to do this.
    • None of the functions documented are described, so I'm left to guess the difference between new MParticle.IdentityRequest, MParticle.Identity.identify, MParticle.Identity.login, MParticle.Identity.logout and MParticle.Identity.modify. There's some description of the corollary functions in the iOS SDK docs, so it shouldn't take much to update the react native docs.
    • What's the difference between request.setUserIdentity('[email protected]', MParticle.UserIdentityType.Email) and var request = new MParticle.IdentityRequest(); request.email = '[email protected]' MParticle.Identity.identify(request);
    • How do we add multiple identifiers in a row? I assume that involves setting request properties sequentially before running MParticle.Identity.identify(request), it would be nice to see an example.
    • Should I be using the same IdentityRequest class instance throughout the app, for example to run login, identify and modify commands?

    Unrelated: pod setup in the docs doesn't indicate specific versions. Auto-linking should solve this.

    Build Failure in React Native Due to Missing mParticle-Apple-SDK Header After Update

    We are facing a problem in our React Native project after updating the react-native-mparticle package from version 2.7.8 to 2.7.9. This update also led to an upgrade of the mParticle-Apple-SDK pod from version 8.12.0 to 8.18.0.

    After installing pods, we noticed mparticle_apple_sdk-swift.h was imported in MPKitAppboy, mParticle-Apple-SDK, and MPKitFirebaseGA4Analytics. However, MPKitAppboy and MPKitFirebaseGA4Analytics showed a 'file not found' error. Initially, we thought it was a compatibility issue with other SDKs. Removing these pods and keeping only mParticle didn't resolve the issue; we encountered a compile-time error stating 'mParticle_Apple_SDK/mParticle_Apple_SDK.h' was missing in mparticle_apple_sdk-swift.h. Below are the error logs.

    /Users/runner/work/1/s/ios/Pods/mParticle-Apple-SDK/mParticle-Apple-SDK/mParticle.m:26:
    In file included from /Users/runner/work/1/s/ios/Pods/mParticle-Apple-SDK/mParticle-Apple-SDK/Swift.h:13:
    /Users/runner/Library/Developer/Xcode/DerivedData/myproject/Build/Intermediates.noindex/ArchiveIntermediates/Myr-target/IntermediateBuildFilesPath/Pods.build/Release-iphoneos/mParticle-Apple-SDK.build/DerivedSources/mParticle_Apple_SDK-Swift.h:237:9: fatal error: 'mParticle_Apple_SDK/mParticle_Apple_SDK.h' file not found
    #import <mParticle_Apple_SDK/mParticle_Apple_SDK.h>
    1 error generated
    

    Here is Swift.h file from mParticle_Apple_SDK for your reference.

    #if defined(__has_include) && __has_include(<mParticle_Apple_SDK/mParticle_Apple_SDK-Swift.h>)
        #import <mParticle_Apple_SDK/mParticle_Apple_SDK-Swift.h>
    #elif defined(__has_include) && __has_include(<mParticle_Apple_SDK_NoLocation/mParticle_Apple_SDK-Swift.h>)
        #import <mParticle_Apple_SDK_NoLocation/mParticle_Apple_SDK-Swift.h>
    #else
        #import "mParticle_Apple_SDK-Swift.h" //in this file we are trying to import <mParticle_Apple_SDK/mParticle_Apple_SDK.h> which is causing the 'file not found' issue
    #endif
    

    My project structure includes the mParticle-Apple-SDK folder under Pods, but there seems to be a path or naming convention issue causing the build to fail.
    I've attempted the usual troubleshooting steps such as cleaning the build folder, running pod install, and verifying the header search paths, but the issue persists. Could you provide guidance on resolving this issue?

    Simulator not running on M1 MacBook?

    Idk why i'm getting this error? I have followed the initial set up doc for mParticle react-native. I'm using an M1 with arch -x86_64 pod install command.

    Screen Shot 2022-08-13 at 9 15 14 PM

    Value cannot be cast from Boolean to String

    Hi,

    I'm using [email protected] and experiencing the issue in the screenshot on Android. is_prepay is a boolean value attribute in the event, it works fine on iOS.

    My workaround for now is:

    track(event) {
        const payload = { ...event.payload };
        // MParticleModule for Android somehow tries to cast Boolean to String which would crash the app.
        if (Platform.OS === "android") {
          Object.keys(payload).forEach((key) => {
            if (typeof payload[key] === "boolean") {
              payload[key] = String(payload[key]);
            }
          })
        }
        MParticle.logEvent(event.name, MPaticle.EventType.Other, payload);
    }
    

    Could you help me to understand the situation here? Did I miss any docs about this issue? Or is this a bug?

    Unable install in expo

    Steps to repro:

    1. Init a new expo project
    2. npx expo prebuild to expose native code
    3. Install react-native-mparticle yarn add react-native-mparticle
    4. Add mParticle to Podfile pod 'mParticle-Apple-SDK', '~> 8'
    5. npx expo run:ios to run in iOS simulator

    This leads to a buildtime error:
    Screenshot 2023-05-04 at 1 29 36 PM

    
    › Planning build
    › Compiling Pods/mParticle-Apple-SDK » MPUploadBuilder.mm
    › Compiling Pods/mParticle-Apple-SDK » MPStateMachine.mm
    › Compiling Pods/mParticle-Apple-SDK » MPSurrogateAppDelegate.m
    › Compiling Pods/mParticle-Apple-SDK » MPTransactionAttributes.m
    
    ❌  (node_modules/expo-modules-core/ios/Swift.h:5:9)
    
      3 | // The generated swift header may depend on some Objective-C declarations,
      4 | // adding dependency imports here to prevent declarations not found errors.
    > 5 | #import <ExpoModulesCore/EXDefines.h>
        |         ^ 'ExpoModulesCore/EXDefines.h' file not found
      6 | #import <ExpoModulesCore/RCTComponentData+Privates.h>
      7 | 
      8 | // When `use_frameworks!` is used, the generated Swift header is inside ExpoModulesCore module.
    
    › Compiling Pods/mParticle-Apple-SDK » MPSearchAdsAttribution.m
    › Compiling Pods/mParticle-Apple-SDK » MPSession.m
    › Compiling Pods/mParticle-Apple-SDK » MPResponseConfig.m
    › Compiling Pods/mParticle-Apple-SDK » MPPromotion.mm
    › Compiling Pods/mParticle-Apple-SDK » MPResponseEvents.mm
    › Compiling Pods/mParticle-Apple-SDK » MPProduct.mm
    

    Am I missing a step?

    com.mparticle:android-core com.mparticle:android-core: compliance warning for Android

    We are getting the following suggestion from google reguarding the mParticle library:
    com.mparticle:android-core com.mparticle:android-core : Consider upgrading to a policy-compliant version of the SDK if available from your SDK provider, or removing the SDK.

    We are using mParticle 2.7.6
    react native 0.68.0
    following the suggestions in this post: https://support.mparticle.com/hc/en-us/articles/6040893457549-Why-is-Google-Play-warning-me-about-a-non-compliant-SDK-version

    We changed in our build.gradle file from: implementation 'com.mparticle:android-core:5+'
    to: implementation 'com.mparticle:android-core:5.35+' in the next build to see if we can get past the rejection then.
    Do you have any other suggestions for this issue?

    Migrate to AndroidX

    Hey,

    We are migrating away from support libraries to disable Jetifier and noticed that one of the dependencies that still has android support libs is coming from rn-mparticle sdk. This can be fixed by migrating to AndroidX dependencies. Could you please have a look?

    > Task :react-native-mparticle:checkJetifier
    The following libraries used by project ':react-native-mparticle' depend on legacy support libraries. To disable Jetifier, you will need to use AndroidX-supported versions of these libraries.
            com.android.support:support-annotations:27.1.1 (Project ':react-native-mparticle', configuration 'debugUnitTestCompileClasspath' -> com.android.support:support-annotations:27.1.1)
    

    As far as I can see it should be simply replacing this dependency https://github.com/mParticle/react-native-mparticle/blob/main/android/build.gradle#L59:

    com.android.support:support-annotations:27.1.1 -> androidx.annotation:annotation:1.2.0
    
    

    mParticle -> Warning: Braze SDK initialized outside of mParticle kit

    Hello amazing community, I am having a few issues during the Braze and mParticle integration.

    Currently, on our production app, our users are being tracked but not identified.

    Braze Dashboard

    image

    On Flipper I am receiving this message:

    mParticle -> Warning: Braze SDK initialized outside of mParticle kit, this will mean Braze settings within the mParticle dashboard such as API key, endpoint URL, flush interval and others will not be respected.
    

    This is my current implementation of AppDelegate.m.

    #import <mParticle-Apple-SDK/mParticle.h>
    #import "mParticle.h"
    #import "AppboyKit.h"
    #import "ABKPushUtils.h"
    #import "AppboyReactUtils.h"
    
    @implementation AppDelegate
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
      RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
      RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                       moduleName:@"APP-PROJECT-NAME"
                                                initialProperties:nil];
    
      NSURL *jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
    
      self.bridge = rootView.bridge;
      self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
      UIViewController *rootViewController = [UIViewController new];
      rootViewController.view = rootView;
      self.window.rootViewController = rootViewController;
      [self.window makeKeyAndVisible];
    
      [[FBSDKApplicationDelegate sharedInstance] application:application
                               didFinishLaunchingWithOptions:launchOptions];
    
      /*
      * mParticle integration
      * documentation on: https://docs.mparticle.com/developers/sdk/react-native/getting-started/
      */
      MParticleOptions *mParticleOptions;
      mParticleOptions = [MParticleOptions optionsWithKey:@"MPARTICLE-KEY" secret:@"MPARTICLE-SECRET"];
    
      [[MParticle sharedInstance] startWithOptions:mParticleOptions];
    
      NSString *brazeIntegrationKey = DEBUG ? @"BRAZE-KEY-DEV" : @"BRAZE-KEY-PROD";
    
      [Appboy startWithApiKey:brazeIntegrationKey
                inApplication:application
            withLaunchOptions:launchOptions
            withAppboyOptions:@{ ABKMinimumTriggerTimeIntervalKey : @1 }];
    
      // Register for user notifications
      if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_9_x_Max) {
        UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        UNAuthorizationOptions options = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
        if (@available(iOS 12.0, *)) {
          options = options | UNAuthorizationOptionProvisional;
        }
        [center requestAuthorizationWithOptions:(options)
                              completionHandler:^(BOOL granted, NSError *_Nullable error) {
                                NSLog(@"Permission granted.");
                                [[Appboy sharedInstance] pushAuthorizationFromUserNotificationCenter:granted];
                              }];
        [center setNotificationCategories:[ABKPushUtils getAppboyUNNotificationCategorySet]];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
      } else {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound) categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
      }
    
      [[AppboyReactUtils sharedInstance] populateInitialUrlFromLaunchOptions:launchOptions];
      [RNSplashScreen show];
    
      return YES;
    }
    
    - (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
      [[Appboy sharedInstance] registerApplication:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
    }
    
    - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
      [[AppboyReactUtils sharedInstance] populateInitialUrlForCategories:response.notification.request.content.userInfo];
      [[Appboy sharedInstance] userNotificationCenter:center didReceiveNotificationResponse:response withCompletionHandler:completionHandler];
    }
    
    - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
      [[Appboy sharedInstance] registerDeviceToken:deviceToken];
    }
    
    @end
    
    
    

    I can see the events on mParticle.

    I have basically two questions for our expert team:

    • How can I solve this Braze warning on Flipper?
    • Why the events from mParticle are not being forwarded to Braze? (Just a few users are able to be identified)

    I followed these tutorials:

    I tried a few things already but I am not able to solve it, thank you for your time.

    Compilation Error

    following line causes Compilation

    if json[@"shouldUploadEvent"] != nil {
    event.shouldUploadEvent = [json[@"shouldUploadEvent"] boolValue]
    }

    Can't build the app after upgrading mParticle-Apple-SDK to 8.13.0

    Hi everyone! Could you please help me understand what I'm doing wrong if I am?

    I'm trying to upgrade the version of mParticle-Apple-SDK to 8.13.0, and for some reason, this issue appears:

    01_mParticle_error_small

    I could've asked it in the repo of mParticle-Apple-SDK directly, but I'm not sure where the problem comes from, so I thought of starting here.

    What I've tried so far:

    • removed node_modules and Pods folders, re-installed deps
    • cleaned pods cache and DerivedData

    My Podfile:

    require_relative '../node_modules/react-native/scripts/react_native_pods'
    require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
    
    platform :ios, '12.4'
    install! 'cocoapods', :deterministic_uuids => false
    
    is_test = ENV['MODE'] == 'e2e'
    # use_flipper!()
    
    def shared_pods
      permissions_path = '../node_modules/react-native-permissions/ios'
      pod 'Permission-AppTrackingTransparency', :path => "#{permissions_path}/AppTrackingTransparency"
      pod 'Permission-LocationWhenInUse', :path => "#{permissions_path}/LocationWhenInUse"
      pod 'Permission-Notifications', :path => "#{permissions_path}/Notifications"
      pod 'react-native-google-maps', :path => '../node_modules/react-native-maps'
      pod 'PayPalCheckout', '~> 0.88.0'
      pod 'FBSDKCoreKit'
      pod 'FBSDKLoginKit'
      pod 'TikTokOpenSDK', '~> 5.0.0'
      pod 'mParticle-Apple-SDK', '~> 8.13.0'
      pod 'mParticle-Appboy', '~> 8.1.0'
    
      config = use_native_modules!
    
      # Flags change depending on the env values.
      flags = get_default_flags()
    
      use_react_native!(
        :path => config[:reactNativePath],
        :hermes_enabled => true,
        :fabric_enabled => flags[:fabric_enabled],
        :flipper_configuration => FlipperConfiguration.enabled,
        :app_path => "#{Pod::Config.instance.installation_root}/.."
      )
    
      inhibit_all_warnings!
    end
    
    target 'myApp' do
      shared_pods
    
    end
    
    target 'myApp-staging' do
      shared_pods
    end
    
    post_install do |installer|
      react_native_post_install(
        installer,
        # Set `mac_catalyst_enabled` to `true` in order to apply patches
        # necessary for Mac Catalyst builds
        :mac_catalyst_enabled => false
      )
      __apply_Xcode_12_5_M1_post_install_workaround(installer)
      installer.pods_project.targets.each do |target|
        target.build_configurations.each do |config|
          config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '12.0'
        end
        if target.respond_to?(:product_type) and target.product_type == "com.apple.product-type.bundle"
          target.build_configurations.each do |config|
              config.build_settings['CODE_SIGNING_ALLOWED'] = 'NO'
          end
        end
      end
      installer.pods_project.build_configurations.each do |config|
        config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64"
      end
    end

    AppDelegate

    02_imports_small

    Screenshot 2023-04-26 at 17 28 20

    Context

    • react-native version: 0.70.6
    • react-native-mparticle version: 2.7.8
    • initial mParticle-Apple-SDK version: 8.10.0

    In general, I'm trying to fix the issue that appeared after I upgraded the version of RN from 0.68 to the current one and then had to bump the react-native-mparticle and migrate from Appboy to Braze.

    I forgot to upgrade native iOS dependencies such as mParticle-Apple-SDK and mParticle-Appboy and I think that could be the reason why one specific part of the integration could be broken. In general, the data forwarding to Braze works great.

    Thanks for your attention! Please let me know if I can give some more details or if I have to raise it in a different repo or even just contact the support team.

    Not able to find specification

    Hello,

    I am running into an issue with the pod install step. My project is on React Native ~0.63 with a previous expo eject.

    The error I receive is the following:

    [!] Unable to find a specification for mParticle-Apple-SDK (~> 8.7)

    You have either:

    • mistyped the name or version.
    • not added the source repo that hosts the Podspec to your Podfile.

    I have tried various version numbers

    Here is the podfile

    require_relative '../node_modules/react-native/scripts/react_native_pods'
    require_relative '../node_modules/react-native-unimodules/cocoapods.rb'
    require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

    source 'https://github.com/brightcove/BrightcoveSpecs.git'
    platform :ios, '11'

    target 'mediapp' do
    use_unimodules!
    config = use_native_modules!

    use_react_native!(:path => config["reactNativePath"])

    pod 'mParticle-Apple-SDK', '~> 8.7'

    end

    thanks for the help

    Could not invoke MParticle.logEvent

    I updated to 2.7.0 which fixed the compile time error (as described in #68), but now when the app is actually running, I receive this error:

    Could not invoke MParticle.logEvent
    
    null
    
    No virtual method info(Ljava/util/map;)Lcom/mparticle/MPEvent$Builder;
    in class Lcom/mparticle/MPEvent$Builder;
    or its super classes (declaration of 'com.mparticle.MPEvent$Builder' appears in
    /data/app/~~3vP3w5TCBYkUUwsEB4-Bog==/<redacted>-4cbNUmsn0n_RM_K_H2Pozg==/base.apk!classes6.dex)
    

    There was no issue before the new android release from yesterday.

    Any advice?

    Missing userId when calling getUserAttributes()

    NativeModules.MParticle.getUserAttributes((error, userAttributes) => {

    Hi team - it appears that the userId is not passed when attempting to use getUserAttributes(). I plan to open a PR for this.

    Also - does getUserAttributes() pull the users attributes from the server or is it pulling from somewhere on the device? My scenario is that I have a boolean flag I am attempting to check and then set, and it appears to not be setting the value via setUserAttribute() because the value is identical locally but not on the server.

    Global Subscription States in Braze via mParticle React Native library

    Hello, I am trying to enable via the mParticle react-native library these settings, but when I try to use the OptOut method does not work.

    From the mParticle documentation: https://docs.mparticle.com/integrations/braze/event/#event-data-mapping

    image

    This is based on calling the OptOut (setOptOut in Android) SDK method. It will be set to opted_in when called with a value of true and will be set to unsubscribed when called with a value of false. Email subscription statuses can also be updated server side by setting the user attribute email_subscribe with a value of subscribed, unsubscribed, or opted_in, which correspond to the Global Subscription States in Braze.
    

    This method is always returning undefined: https://github.com/mParticle/react-native-mparticle

    var isOptedOut = MParticle.getOptOut();
    MParticle.setOptOut(!isOptedOut);
    

    Do you have any idea how can I make this work or if I am missing some important steps?

    Module uses old part of the mParticle Android SDK

    Last week, version 5.43.0 of the mParticle Android SDK was released. This commit changed the type of the first parameter of getUserAttributes from UserAttributeListener to UserAttributeType. This native module calls that method but passes in an object of the old type (here). Given that the build.gradle file simply pulls in the latest version, this breaks the module itself. It should be updated to use the new SDK, or be limited to using the version before.

    'mParticle.h' file not found

    I am getting 'mParticle.h' file not found error when trying to build the app.

    /Users/<user>/Documents/MyApp/node_modules/react-native-mparticle/ios/RNMParticle/RNMParticle.m:2:9: fatal error: 'mParticle.h' file not found
    #import "mParticle.h"
    

    Environment
    Node: 18.16.0
    Xcode: 14.3
    Mac: 13.3.1 Intel

    package.json

    "react": "18.2.0",
    "react-native": "0.72.4",
    "react-native-mparticle": "^2.7.8"
    

    Podfile

    # Resolve react_native_pods.rb with node to allow for hoisting
    require Pod::Executable.execute_command('node', ['-p',
      'require.resolve(
        "react-native/scripts/react_native_pods.rb",
        {paths: [process.argv[1]]},
      )', __dir__]).strip
    
    platform :ios, min_ios_version_supported
    prepare_react_native_project!
    
    # If you are using a `react-native-flipper` your iOS build will fail when `NO_FLIPPER=1` is set.
    # because `react-native-flipper` depends on (FlipperKit,...) that will be excluded
    #
    # To fix this you can also exclude `react-native-flipper` using a `react-native.config.js`
    # ```js
    # module.exports = {
    #   dependencies: {
    #     ...(process.env.NO_FLIPPER ? { 'react-native-flipper': { platforms: { ios: null } } } : {}),
    # ```
    flipper_config = ENV['NO_FLIPPER'] == "1" ? FlipperConfiguration.disabled : FlipperConfiguration.enabled
    
    linkage = ENV['USE_FRAMEWORKS']
    if linkage != nil
      Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green
      use_frameworks! :linkage => linkage.to_sym
    end
    
    target 'AwesomeProject' do
      config = use_native_modules!
      use_frameworks! :linkage => :static
      
      pod 'mParticle-Apple-SDK', '~> 8'
    
      # Flags change depending on the env values.
      flags = get_default_flags()
    
      use_react_native!(
        :path => config[:reactNativePath],
        # Hermes is now enabled by default. Disable by setting this flag to false.
        :hermes_enabled => flags[:hermes_enabled],
        :fabric_enabled => flags[:fabric_enabled],
        # Enables Flipper.
        #
        # Note that if you have use_frameworks! enabled, Flipper will not work and
        # you should disable the next line.
        #:flipper_configuration => flipper_config,
        # An absolute path to your application root.
        :app_path => "#{Pod::Config.instance.installation_root}/.."
      )
    
      target 'AwesomeProjectTests' do
        inherit! :complete
        # Pods for testing
      end
    
      post_install do |installer|
        # https://github.com/facebook/react-native/blob/main/packages/react-native/scripts/react_native_pods.rb#L197-L202
        react_native_post_install(
          installer,
          config[:reactNativePath],
          :mac_catalyst_enabled => false
        )
        __apply_Xcode_12_5_M1_post_install_workaround(installer)
      end
    end
    

    I followed following documentation.
    https://docs.mparticle.com/developers/sdk/react-native/getting-started/

    Please note that I am using use_frameworks! :linkage => :static in Podfile as I have used rnfirebase.

    Thanks

    'mParticle.h' file not found

    Hello,

    After installing react-native-mparticle as described in the docs I get the following error:

    /node_modules/react-native-mparticle/ios/RNMParticle/RNMParticle.m:2:9: 'mParticle.h' file not found

    question: isLoggedIn flag.

    Withmparticle-web-sdk we can currently use user.isLoggedIn() to check whether a user is logged in or not; I dug into this repo's code but I couldn't find any equivalent function to check this.

    Is this supported by react-native-mparticle or maybe we should rely on some alternative approach like checking for userIdentities.CustomerId as mentioned in the android docs (https://docs.mparticle.com/developers/sdk/android/javadocs/com/mparticle/identity/MParticleUserImpl.html#isLoggedIn())?

    Thanks.

    [iOS] App won't build after upgrading to react-native 0.73

    Hello and happy new year.
    Sorry in advance if this is not the right repo to report this issue.
    This error occurred after I tried to upgrade react-native from 0.72.6 to 0.73.1.

    Error message

    When I try to build the iOS application I get the following error from mParticle-Google-Analytics-Firebase-GA4 pod

    'mParticle_Apple_SDK-Swift.h' file not found

    Setup

    react-native
    0.73.1

    react-native-mparticle
    2.7.9

    Podfile

     pod 'mParticle-Apple-SDK', '~> 8'
     pod 'mParticle-BranchMetrics', '~> 8'
     pod 'mParticle-Optimizely', '~> 8'
     pod 'mParticle-Appboy', '~> 8'
     pod 'mParticle-Google-Analytics-Firebase-GA4', '~> 8'
    

    If there are any other information that I can provide, please let me know.

    Thank you.

    Recommend Projects

    • React photo React

      A declarative, efficient, and flexible JavaScript library for building user interfaces.

    • Vue.js photo Vue.js

      🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

    • Typescript photo Typescript

      TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

    • TensorFlow photo TensorFlow

      An Open Source Machine Learning Framework for Everyone

    • Django photo Django

      The Web framework for perfectionists with deadlines.

    • D3 photo D3

      Bring data to life with SVG, Canvas and HTML. 📊📈🎉

    Recommend Topics

    • javascript

      JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

    • web

      Some thing interesting about web. New door for the world.

    • server

      A server is a program made to process requests and deliver data to clients.

    • Machine learning

      Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

    • Game

      Some thing interesting about game, make everyone happy.

    Recommend Org

    • Facebook photo Facebook

      We are working to build community through open source technology. NB: members must have two-factor auth.

    • Microsoft photo Microsoft

      Open source projects and samples from Microsoft.

    • Google photo Google

      Google ❤️ Open Source for everyone.

    • D3 photo D3

      Data-Driven Documents codes.