Implementing Google Consent for GDPR with React Native

Tiempo de lectura: 2 minutos

Today we are going to learn how we can implement the GDPR consent message with React Native.

Let’s install the following library (https://www.npmjs.com/package/@ulangi/react-native-ad-consent)

npm install @ulangi/react-native-ad-consent --save

Now let’s add this key in info.plist of iOS:

<key>GADDelayAppMeasurementInit</key>
<true/>

Now we open AndroidManifest.xml in case of Android. And add:

<meta-data android:name="com.google.android.gms.ads.DELAY_APP_MEASUREMENT_INIT"
        android:value="true"/>
      <uses-library android:name="org.apache.http.legacy" android:required="false"/>

And now we create our component called consentAdmob.ts

import RNAdConsent from 'ulangi/react-native-ad-consent';

async function obtenerConsentimientoUsuario(publisherId) {
  const consentStatus = await RNAdConsent.requestConsentInfoUpdate({
    publisherId,
  });

  if (consentStatus === RNAdConsent.UNKNOWN) {
    const isInEeaOrUnknown = await RNAdConsent.isRequestLocationInEeaOrUnknown();

    if (isInEeaOrUnknown) {
      const adProviders = await RNAdConsent.getAdProviders();
      
      // You can do something with the ad providers, for example, show a custom modal

      await RNAdConsent.setConsentStatus(RNAdConsent.PERSONALIZED);
    }
  }
}

async function mostrarAlertAdmobConsent(adAppId, publisherId) {
  const consentStatus = await RNAdConsent.requestConsentInfoUpdate({
    publisherId,
  });

  if (consentStatus === RNAdConsent.UNKNOWN) {
    const formResponse = await RNAdConsent.showGoogleConsentForm({
      privacyPolicyUrl: "https://your-privacy-link.com",
      shouldOfferAdFree: true,
    });
    
    if (formResponse === RNAdConsent.PREFERS_AD_FREE) {
      // Do something specific when the user prefers an ad-free experience
    } else {
      await RNAdConsent.setConsentStatus(formResponse);
    }
  }

  // Then, initialize AdMob
  await adMob.initialize(adAppId);
}

To use the functions we provide, you should call obtenerConsentimientoUsuario before showing the consent form and initializing AdMob with the function mostrarAlertAdmobConsent. Make sure to provide the proper values for adAppId and publisherId. Also, remember to add: «https://your-privacy-link.com» for your app’s privacy policy URL.

Here’s an example of how you could use these functions:

// Define your publisherId and adAppId values
const publisherId = "pub-1234567890";
const adAppId = "your_admob_app_id";

// Call the function to get user consent
await obtenerConsentimientoUsuario(publisherId);

// Call the function to show the consent form and then initialize AdMob
await mostrarAlertAdmobConsent(adAppId, publisherId);

Leave a Comment