(
89 | null
90 | );
91 | const [adLoaded, setAdLoaded] = useState(false);
92 | const [adDismissed, setAdDismissed] = useState(false);
93 |
94 | // ...
95 |
96 | return (
97 |
98 |
109 | );
110 | }
111 | ```
112 |
--------------------------------------------------------------------------------
/docs/docs/usage/npa.mdx:
--------------------------------------------------------------------------------
1 | ---
2 | title: Non Personalized Ads
3 | ---
4 |
5 | To load non-personalized ads only, set `requestNonPersonalizedAdsOnly` to `true` in [RequestOptions](/docs/api/types/RequestOptions) for your ads.
6 |
7 | ```tsx title=Hook
8 | const requestOptions = {
9 | requestNonPersonalizedAdsOnly: true,
10 | };
11 |
12 | const rewardedAd = useRewardedAd(UNIT_ID_REWARDED, {
13 | requestOptions,
14 | });
15 | ```
16 |
17 | ```tsx title=Class
18 | const requestOptions = {
19 | requestNonPersonalizedAdsOnly: true,
20 | };
21 |
22 | // Requesting npa only in class instance (only for this request)
23 | interstitialAd
24 | .requestAd(requestOptions)
25 | .catch((e: Error) => setAdLoadError(e))
26 | .then(() => setAdLoaded(true));
27 |
28 | // Requesting npa only in class instance (for all requests in this ad instance)
29 | interstitialAd.setRequestOptions(requestOptions);
30 | ```
31 |
32 | ```tsx title=BannerAd
33 | const requestOptions = {
34 | requestNonPersonalizedAdsOnly: true,
35 | };
36 |
37 | ;
42 | ```
43 |
--------------------------------------------------------------------------------
/docs/docs/usage/remove-ads.mdx:
--------------------------------------------------------------------------------
1 | ---
2 | title: Removing ads conditionally
3 | ---
4 |
5 | WIP
6 |
--------------------------------------------------------------------------------
/docs/docusaurus.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | title: 'React Native Admob Native Ads',
3 | tagline: 'Admob for React Native with powerful hooks',
4 | url: 'https://react-native-admob.github.io/',
5 | baseUrl: '/admob/',
6 | trailingSlash: false,
7 | onBrokenLinks: 'throw',
8 | onBrokenMarkdownLinks: 'warn',
9 | favicon: 'img/favicon.ico',
10 | organizationName: 'react-native-admob',
11 | projectName: 'admob',
12 | themeConfig: {
13 | navbar: {
14 | title: 'React Native Admob',
15 | items: [
16 | {
17 | to: 'docs/installation',
18 | activeBasePath: 'docs',
19 | label: 'Docs',
20 | position: 'left',
21 | },
22 | {
23 | href: 'https://github.com/react-native-admob/admob',
24 | label: 'GitHub',
25 | position: 'right',
26 | },
27 | ],
28 | },
29 | footer: {
30 | style: 'dark',
31 | links: [
32 | {
33 | title: 'Links',
34 | items: [
35 | {
36 | label: 'GitHub',
37 | href: 'https://github.com/react-native-admob/admob',
38 | },
39 | ],
40 | },
41 | ],
42 | copyright: `Copyright © ${new Date().getFullYear()} Jay Kim, Built with Docusaurus.`,
43 | },
44 | prism: {
45 | additionalLanguages: ['ruby'],
46 | },
47 | },
48 | presets: [
49 | [
50 | '@docusaurus/preset-classic',
51 | {
52 | docs: {
53 | sidebarPath: require.resolve('./sidebars.js'),
54 | sidebarItemsGenerator: async function ({
55 | defaultSidebarItemsGenerator,
56 | docs,
57 | ...args
58 | }) {
59 | const filteredDocs = docs.filter(
60 | (doc) =>
61 | !doc.id.toLowerCase().includes('fullscreenad') ||
62 | doc.id.toLowerCase().includes('options')
63 | );
64 | const sidebarItems = await defaultSidebarItemsGenerator({
65 | docs: filteredDocs,
66 | ...args,
67 | });
68 | return sidebarItems;
69 | },
70 | editUrl:
71 | 'https://github.com/react-native-admob/admob/edit/master/docs/',
72 | remarkPlugins: [
73 | [require('@docusaurus/remark-plugin-npm2yarn'), { sync: true }],
74 | ],
75 | },
76 | theme: {
77 | customCss: require.resolve('./src/css/custom.css'),
78 | },
79 | },
80 | ],
81 | ],
82 | };
83 |
--------------------------------------------------------------------------------
/docs/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "docs",
3 | "version": "0.0.0",
4 | "private": true,
5 | "scripts": {
6 | "docusaurus": "docusaurus",
7 | "start": "docusaurus start",
8 | "build": "docusaurus build",
9 | "swizzle": "docusaurus swizzle",
10 | "deploy": "docusaurus deploy",
11 | "serve": "docusaurus serve",
12 | "clear": "docusaurus clear"
13 | },
14 | "dependencies": {
15 | "@docusaurus/core": "2.0.0-beta.9",
16 | "@docusaurus/preset-classic": "2.0.0-beta.9",
17 | "@docusaurus/remark-plugin-npm2yarn": "^2.0.0-beta.9",
18 | "@mdx-js/react": "^1.6.22",
19 | "clsx": "^1.1.1",
20 | "react": "^17.0.2",
21 | "react-dom": "^17.0.2"
22 | },
23 | "browserslist": {
24 | "production": [
25 | ">0.5%",
26 | "not dead",
27 | "not op_mini all"
28 | ],
29 | "development": [
30 | "last 1 chrome version",
31 | "last 1 firefox version",
32 | "last 1 safari version"
33 | ]
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/docs/sidebars.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | docsSidebar: [{ type: 'autogenerated', dirName: '.' }],
3 | };
4 |
--------------------------------------------------------------------------------
/docs/src/css/custom.css:
--------------------------------------------------------------------------------
1 | /* stylelint-disable docusaurus/copyright-header */
2 | /**
3 | * Any CSS included here will be global. The classic template
4 | * bundles Infima by default. Infima is a CSS framework designed to
5 | * work well for content-centric websites.
6 | */
7 |
8 | /* You can override the default Infima variables here. */
9 | :root {
10 | --ifm-color-primary-lightest: #609eef;
11 | --ifm-color-primary-lighter: #3d88ec;
12 | --ifm-color-primary-light: #3181ea;
13 | --ifm-color-primary: #1a73e8;
14 | --ifm-color-primary-dark: #1567d3;
15 | --ifm-color-primary-darker: #1461c7;
16 | --ifm-color-primary-darkest: #1050a4;
17 | --ifm-code-font-size: 95%;
18 | }
19 |
20 | .docusaurus-highlight-code-line {
21 | background-color: #161a1d;
22 | display: block;
23 | margin: 0 calc(-1 * var(--ifm-pre-padding));
24 | padding: 0 var(--ifm-pre-padding);
25 | }
26 |
--------------------------------------------------------------------------------
/docs/src/pages/styles.module.css:
--------------------------------------------------------------------------------
1 | /* stylelint-disable docusaurus/copyright-header */
2 |
3 | /**
4 | * CSS files with the .module.css suffix will be treated as CSS modules
5 | * and scoped locally.
6 | */
7 |
8 | .heroBanner {
9 | padding: 4rem 0;
10 | text-align: center;
11 | position: relative;
12 | overflow: hidden;
13 | background-color: #4285F4;
14 | }
15 |
16 | .hero__title {
17 | color:#EA4335;
18 | }
19 |
20 | @media screen and (max-width: 966px) {
21 | .heroBanner {
22 | padding: 2rem;
23 | }
24 | }
25 |
26 | .buttons {
27 | display: flex;
28 | align-items: center;
29 | justify-content: center;
30 | }
31 |
32 | .features {
33 | display: flex;
34 | align-items: center;
35 | padding: 2rem 0;
36 | width: 100%;
37 | }
38 |
39 | .featureImage {
40 | height: 200px;
41 | width: 200px;
42 | }
43 |
--------------------------------------------------------------------------------
/docs/static/.nojekyll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/react-native-admob/admob/4b24e57308aa2dd0e28a6eab1d90ae81576e69b2/docs/static/.nojekyll
--------------------------------------------------------------------------------
/docs/static/img/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/react-native-admob/admob/4b24e57308aa2dd0e28a6eab1d90ae81576e69b2/docs/static/img/favicon.ico
--------------------------------------------------------------------------------
/docs/static/img/logo_admob.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/react-native-admob/admob/4b24e57308aa2dd0e28a6eab1d90ae81576e69b2/docs/static/img/logo_admob.png
--------------------------------------------------------------------------------
/docs/static/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
9 |
12 | React Native Admob Native Ads
13 |
14 |
15 | If you are not redirected automatically, follow this
16 | link.
17 |
18 |
--------------------------------------------------------------------------------
/example/android/app/debug.keystore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/react-native-admob/admob/4b24e57308aa2dd0e28a6eab1d90ae81576e69b2/example/android/app/debug.keystore
--------------------------------------------------------------------------------
/example/android/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
--------------------------------------------------------------------------------
/example/android/app/src/debug/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/example/android/app/src/debug/java/com/example/rnadmob/ReactNativeFlipper.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) Facebook, Inc. and its affiliates.
3 | *
4 | * This source code is licensed under the MIT license found in the LICENSE file in the root
5 | * directory of this source tree.
6 | */
7 | package com.example.rnadmob;
8 |
9 | import android.content.Context;
10 | import com.facebook.flipper.android.AndroidFlipperClient;
11 | import com.facebook.flipper.android.utils.FlipperUtils;
12 | import com.facebook.flipper.core.FlipperClient;
13 | import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin;
14 | import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin;
15 | import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin;
16 | import com.facebook.flipper.plugins.inspector.DescriptorMapping;
17 | import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin;
18 | import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor;
19 | import com.facebook.flipper.plugins.network.NetworkFlipperPlugin;
20 | import com.facebook.flipper.plugins.react.ReactFlipperPlugin;
21 | import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin;
22 | import com.facebook.react.ReactInstanceManager;
23 | import com.facebook.react.bridge.ReactContext;
24 | import com.facebook.react.modules.network.NetworkingModule;
25 | import okhttp3.OkHttpClient;
26 |
27 | public class ReactNativeFlipper {
28 | public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
29 | if (FlipperUtils.shouldEnableFlipper(context)) {
30 | final FlipperClient client = AndroidFlipperClient.getInstance(context);
31 | client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults()));
32 | client.addPlugin(new ReactFlipperPlugin());
33 | client.addPlugin(new DatabasesFlipperPlugin(context));
34 | client.addPlugin(new SharedPreferencesFlipperPlugin(context));
35 | client.addPlugin(CrashReporterPlugin.getInstance());
36 | NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
37 | NetworkingModule.setCustomClientBuilder(
38 | new NetworkingModule.CustomClientBuilder() {
39 | @Override
40 | public void apply(OkHttpClient.Builder builder) {
41 | builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
42 | }
43 | });
44 | client.addPlugin(networkFlipperPlugin);
45 | client.start();
46 | // Fresco Plugin needs to ensure that ImagePipelineFactory is initialized
47 | // Hence we run if after all native modules have been initialized
48 | ReactContext reactContext = reactInstanceManager.getCurrentReactContext();
49 | if (reactContext == null) {
50 | reactInstanceManager.addReactInstanceEventListener(
51 | new ReactInstanceManager.ReactInstanceEventListener() {
52 | @Override
53 | public void onReactContextInitialized(ReactContext reactContext) {
54 | reactInstanceManager.removeReactInstanceEventListener(this);
55 | reactContext.runOnNativeModulesQueueThread(
56 | new Runnable() {
57 | @Override
58 | public void run() {
59 | client.addPlugin(new FrescoFlipperPlugin());
60 | }
61 | });
62 | }
63 | });
64 | } else {
65 | client.addPlugin(new FrescoFlipperPlugin());
66 | }
67 | }
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/example/android/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
13 |
20 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/example/android/app/src/main/java/com/example/rnadmob/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.example.rnadmob;
2 |
3 | import android.os.Bundle;
4 |
5 | import com.facebook.react.ReactActivity;
6 | import com.zoontek.rnbootsplash.RNBootSplash;
7 |
8 | public class MainActivity extends ReactActivity {
9 |
10 | /**
11 | * Returns the name of the main component registered from JavaScript. This is used to schedule
12 | * rendering of the component.
13 | */
14 | @Override
15 | protected String getMainComponentName() {
16 | return "AdmobExample";
17 | }
18 |
19 | @Override
20 | protected void onCreate(Bundle savedInstanceState) {
21 | super.onCreate(null);
22 | RNBootSplash.init(R.drawable.bootsplash, MainActivity.this);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/example/android/app/src/main/java/com/example/rnadmob/MainApplication.java:
--------------------------------------------------------------------------------
1 | package com.example.rnadmob;
2 |
3 | import android.app.Application;
4 | import android.content.Context;
5 |
6 | import com.facebook.react.PackageList;
7 | import com.facebook.react.ReactApplication;
8 | import com.facebook.react.ReactNativeHost;
9 | import com.facebook.react.ReactPackage;
10 | import com.facebook.react.ReactInstanceManager;
11 | import com.facebook.soloader.SoLoader;
12 |
13 | import java.lang.reflect.InvocationTargetException;
14 | import java.util.List;
15 |
16 | import com.rnadmob.admob.RNAdMobPackage;
17 |
18 | public class MainApplication extends Application implements ReactApplication {
19 |
20 | private final ReactNativeHost mReactNativeHost =
21 | new ReactNativeHost(this) {
22 | @Override
23 | public boolean getUseDeveloperSupport() {
24 | return BuildConfig.DEBUG;
25 | }
26 |
27 | @Override
28 | protected List getPackages() {
29 | List packages = new PackageList(this).getPackages();
30 | packages.add(new RNAdMobPackage());
31 | return packages;
32 | }
33 |
34 | @Override
35 | protected String getJSMainModuleName() {
36 | return "index";
37 | }
38 | };
39 |
40 | @Override
41 | public ReactNativeHost getReactNativeHost() {
42 | return mReactNativeHost;
43 | }
44 |
45 | @Override
46 | public void onCreate() {
47 | super.onCreate();
48 | SoLoader.init(this, /* native exopackage */ false);
49 | initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); // Remove this line if you don't want Flipper enabled
50 | }
51 |
52 | /**
53 | * Loads Flipper in React Native templates.
54 | *
55 | * @param context
56 | */
57 | private static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
58 | if (BuildConfig.DEBUG) {
59 | try {
60 | /*
61 | We use reflection here to pick up the class that initializes Flipper,
62 | since Flipper library is not available in release mode
63 | */
64 | Class> aClass = Class.forName("com.example.rnadmob.ReactNativeFlipper");
65 | aClass
66 | .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
67 | .invoke(null, context, reactInstanceManager);
68 | } catch (ClassNotFoundException e) {
69 | e.printStackTrace();
70 | } catch (NoSuchMethodException e) {
71 | e.printStackTrace();
72 | } catch (IllegalAccessException e) {
73 | e.printStackTrace();
74 | } catch (InvocationTargetException e) {
75 | e.printStackTrace();
76 | }
77 | }
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/example/android/app/src/main/res/drawable/bootsplash.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | -
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-hdpi/bootsplash_logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/react-native-admob/admob/4b24e57308aa2dd0e28a6eab1d90ae81576e69b2/example/android/app/src/main/res/mipmap-hdpi/bootsplash_logo.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/react-native-admob/admob/4b24e57308aa2dd0e28a6eab1d90ae81576e69b2/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/react-native-admob/admob/4b24e57308aa2dd0e28a6eab1d90ae81576e69b2/example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-mdpi/bootsplash_logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/react-native-admob/admob/4b24e57308aa2dd0e28a6eab1d90ae81576e69b2/example/android/app/src/main/res/mipmap-mdpi/bootsplash_logo.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/react-native-admob/admob/4b24e57308aa2dd0e28a6eab1d90ae81576e69b2/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/react-native-admob/admob/4b24e57308aa2dd0e28a6eab1d90ae81576e69b2/example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xhdpi/bootsplash_logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/react-native-admob/admob/4b24e57308aa2dd0e28a6eab1d90ae81576e69b2/example/android/app/src/main/res/mipmap-xhdpi/bootsplash_logo.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/react-native-admob/admob/4b24e57308aa2dd0e28a6eab1d90ae81576e69b2/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/react-native-admob/admob/4b24e57308aa2dd0e28a6eab1d90ae81576e69b2/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xxhdpi/bootsplash_logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/react-native-admob/admob/4b24e57308aa2dd0e28a6eab1d90ae81576e69b2/example/android/app/src/main/res/mipmap-xxhdpi/bootsplash_logo.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/react-native-admob/admob/4b24e57308aa2dd0e28a6eab1d90ae81576e69b2/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/react-native-admob/admob/4b24e57308aa2dd0e28a6eab1d90ae81576e69b2/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xxxhdpi/bootsplash_logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/react-native-admob/admob/4b24e57308aa2dd0e28a6eab1d90ae81576e69b2/example/android/app/src/main/res/mipmap-xxxhdpi/bootsplash_logo.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/react-native-admob/admob/4b24e57308aa2dd0e28a6eab1d90ae81576e69b2/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/react-native-admob/admob/4b24e57308aa2dd0e28a6eab1d90ae81576e69b2/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 | #FFFFFF
3 |
4 |
--------------------------------------------------------------------------------
/example/android/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Admob Example
3 |
4 |
--------------------------------------------------------------------------------
/example/android/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
8 |
9 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/example/android/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | ext {
5 | buildToolsVersion = "30.0.2"
6 | minSdkVersion = 21
7 | compileSdkVersion = 31
8 | targetSdkVersion = 31
9 | ndkVersion = "21.4.7075529"
10 | }
11 | repositories {
12 | google()
13 | mavenCentral()
14 | }
15 | dependencies {
16 | classpath('com.android.tools.build:gradle:7.0.4')
17 |
18 | // NOTE: Do not place your application dependencies here; they belong
19 | // in the individual module build.gradle files
20 | }
21 | }
22 |
23 | allprojects {
24 | repositories {
25 | maven {
26 | // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
27 | url("$rootDir/../node_modules/react-native/android")
28 | }
29 | maven {
30 | // Android JSC is installed from npm
31 | url("$rootDir/../node_modules/jsc-android/dist")
32 | }
33 | mavenCentral {
34 | // We don't want to fetch react-native from Maven Central as there are
35 | // older versions over there.
36 | content {
37 | excludeGroup "com.facebook.react"
38 | }
39 | }
40 | google()
41 | maven { url 'https://www.jitpack.io' }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/example/android/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
19 |
20 | android.useAndroidX=true
21 | android.enableJetifier=true
22 | FLIPPER_VERSION=0.99.0
23 |
24 | org.gradle.jvmargs=-Xmx1024m
25 |
--------------------------------------------------------------------------------
/example/android/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/react-native-admob/admob/4b24e57308aa2dd0e28a6eab1d90ae81576e69b2/example/android/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/example/android/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-all.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/example/android/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
--------------------------------------------------------------------------------
/example/android/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'AdmobExample'
2 |
3 | apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
4 |
5 | include ':react-native-admob_admob'
6 | project(':react-native-admob_admob').projectDir = new File(rootProject.projectDir, '../../android')
7 | include ':app'
8 |
--------------------------------------------------------------------------------
/example/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "AdmobExample",
3 | "displayName": "Admob Example"
4 | }
5 |
--------------------------------------------------------------------------------
/example/assets/logo_admob.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/react-native-admob/admob/4b24e57308aa2dd0e28a6eab1d90ae81576e69b2/example/assets/logo_admob.png
--------------------------------------------------------------------------------
/example/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | presets: ['module:metro-react-native-babel-preset'],
3 | plugins: [
4 | [
5 | 'module-resolver',
6 | {
7 | alias: {
8 | '@react-native-admob/admob': '../src',
9 | },
10 | },
11 | ],
12 | ],
13 | };
14 |
--------------------------------------------------------------------------------
/example/index.js:
--------------------------------------------------------------------------------
1 | import { AppRegistry } from 'react-native';
2 |
3 | import App from './src/App';
4 | import { name as appName } from './app.json';
5 |
6 | AppRegistry.registerComponent(appName, () => App);
7 |
--------------------------------------------------------------------------------
/example/ios/AdmobExample.xcodeproj/xcshareddata/xcschemes/AdmobExample.xcscheme:
--------------------------------------------------------------------------------
1 |
2 |
5 |
8 |
9 |
15 |
21 |
22 |
23 |
29 |
35 |
36 |
37 |
38 |
39 |
44 |
45 |
51 |
52 |
53 |
54 |
55 |
56 |
66 |
68 |
74 |
75 |
76 |
77 |
83 |
85 |
91 |
92 |
93 |
94 |
96 |
97 |
100 |
101 |
102 |
--------------------------------------------------------------------------------
/example/ios/AdmobExample.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/example/ios/AdmobExample.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/example/ios/AdmobExample/AppDelegate.h:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) Facebook, Inc. and its affiliates.
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | */
7 |
8 | #import
9 | #import
10 |
11 | @interface AppDelegate : UIResponder
12 |
13 | @property (nonatomic, strong) UIWindow *window;
14 |
15 | @end
16 |
--------------------------------------------------------------------------------
/example/ios/AdmobExample/AppDelegate.m:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) Facebook, Inc. and its affiliates.
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | */
7 |
8 | #import "AppDelegate.h"
9 |
10 | #import
11 | #import
12 | #import
13 |
14 | #ifdef FB_SONARKIT_ENABLED
15 | #import
16 | #import
17 | #import
18 | #import
19 | #import
20 | #import
21 | static void InitializeFlipper(UIApplication *application) {
22 | FlipperClient *client = [FlipperClient sharedClient];
23 | SKDescriptorMapper *layoutDescriptorMapper = [[SKDescriptorMapper alloc] initWithDefaults];
24 | [client addPlugin:[[FlipperKitLayoutPlugin alloc] initWithRootNode:application withDescriptorMapper:layoutDescriptorMapper]];
25 | [client addPlugin:[[FKUserDefaultsPlugin alloc] initWithSuiteName:nil]];
26 | [client addPlugin:[FlipperKitReactPlugin new]];
27 | [client addPlugin:[[FlipperKitNetworkPlugin alloc] initWithNetworkAdapter:[SKIOSNetworkAdapter new]]];
28 | [client start];
29 | }
30 | #endif
31 |
32 | #import "RNBootSplash.h"
33 |
34 | @implementation AppDelegate
35 |
36 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
37 | {
38 | #ifdef FB_SONARKIT_ENABLED
39 | InitializeFlipper(application);
40 | #endif
41 | RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
42 | RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
43 | moduleName:@"AdmobExample"
44 | initialProperties:nil];
45 |
46 | rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
47 |
48 | self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
49 | UIViewController *rootViewController = [UIViewController new];
50 | rootViewController.view = rootView;
51 | self.window.rootViewController = rootViewController;
52 | [self.window makeKeyAndVisible];
53 |
54 | [RNBootSplash initWithStoryboard:@"BootSplash" rootView:rootView];
55 |
56 | return YES;
57 | }
58 |
59 | - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
60 | {
61 | #if DEBUG
62 | return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
63 | #else
64 | return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
65 | #endif
66 | }
67 |
68 | @end
69 |
--------------------------------------------------------------------------------
/example/ios/AdmobExample/BootSplash.storyboard:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/example/ios/AdmobExample/Images.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "iphone",
5 | "scale" : "2x",
6 | "size" : "20x20"
7 | },
8 | {
9 | "idiom" : "iphone",
10 | "scale" : "3x",
11 | "size" : "20x20"
12 | },
13 | {
14 | "idiom" : "iphone",
15 | "scale" : "2x",
16 | "size" : "29x29"
17 | },
18 | {
19 | "idiom" : "iphone",
20 | "scale" : "3x",
21 | "size" : "29x29"
22 | },
23 | {
24 | "idiom" : "iphone",
25 | "scale" : "2x",
26 | "size" : "40x40"
27 | },
28 | {
29 | "idiom" : "iphone",
30 | "scale" : "3x",
31 | "size" : "40x40"
32 | },
33 | {
34 | "idiom" : "iphone",
35 | "scale" : "2x",
36 | "size" : "60x60"
37 | },
38 | {
39 | "idiom" : "iphone",
40 | "scale" : "3x",
41 | "size" : "60x60"
42 | },
43 | {
44 | "idiom" : "ios-marketing",
45 | "scale" : "1x",
46 | "size" : "1024x1024"
47 | }
48 | ],
49 | "info" : {
50 | "author" : "xcode",
51 | "version" : 1
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/example/ios/AdmobExample/Images.xcassets/BootSplashLogo.imageset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images": [
3 | {
4 | "idiom": "universal",
5 | "filename": "bootsplash_logo.png",
6 | "scale": "1x"
7 | },
8 | {
9 | "idiom": "universal",
10 | "filename": "bootsplash_logo@2x.png",
11 | "scale": "2x"
12 | },
13 | {
14 | "idiom": "universal",
15 | "filename": "bootsplash_logo@3x.png",
16 | "scale": "3x"
17 | }
18 | ],
19 | "info": {
20 | "version": 1,
21 | "author": "xcode"
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/example/ios/AdmobExample/Images.xcassets/BootSplashLogo.imageset/bootsplash_logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/react-native-admob/admob/4b24e57308aa2dd0e28a6eab1d90ae81576e69b2/example/ios/AdmobExample/Images.xcassets/BootSplashLogo.imageset/bootsplash_logo.png
--------------------------------------------------------------------------------
/example/ios/AdmobExample/Images.xcassets/BootSplashLogo.imageset/bootsplash_logo@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/react-native-admob/admob/4b24e57308aa2dd0e28a6eab1d90ae81576e69b2/example/ios/AdmobExample/Images.xcassets/BootSplashLogo.imageset/bootsplash_logo@2x.png
--------------------------------------------------------------------------------
/example/ios/AdmobExample/Images.xcassets/BootSplashLogo.imageset/bootsplash_logo@3x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/react-native-admob/admob/4b24e57308aa2dd0e28a6eab1d90ae81576e69b2/example/ios/AdmobExample/Images.xcassets/BootSplashLogo.imageset/bootsplash_logo@3x.png
--------------------------------------------------------------------------------
/example/ios/AdmobExample/Images.xcassets/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "info" : {
3 | "version" : 1,
4 | "author" : "xcode"
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/example/ios/AdmobExample/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleDisplayName
8 | Admob Example
9 | CFBundleExecutable
10 | $(EXECUTABLE_NAME)
11 | CFBundleIdentifier
12 | $(PRODUCT_BUNDLE_IDENTIFIER)
13 | CFBundleInfoDictionaryVersion
14 | 6.0
15 | CFBundleName
16 | $(PRODUCT_NAME)
17 | CFBundlePackageType
18 | APPL
19 | CFBundleShortVersionString
20 | 1.0
21 | CFBundleSignature
22 | ????
23 | CFBundleVersion
24 | 1
25 | GADApplicationIdentifier
26 | ca-app-pub-3940256099942544~1458002511
27 | LSRequiresIPhoneOS
28 |
29 | NSAppTransportSecurity
30 |
31 | NSAllowsArbitraryLoads
32 |
33 | NSExceptionDomains
34 |
35 | localhost
36 |
37 | NSExceptionAllowsInsecureHTTPLoads
38 |
39 |
40 |
41 |
42 | NSLocationWhenInUseUsageDescription
43 |
44 | UILaunchStoryboardName
45 | BootSplash
46 | UIRequiredDeviceCapabilities
47 |
48 | armv7
49 |
50 | UISupportedInterfaceOrientations
51 |
52 | UIInterfaceOrientationPortrait
53 | UIInterfaceOrientationLandscapeLeft
54 | UIInterfaceOrientationLandscapeRight
55 |
56 | UIViewControllerBasedStatusBarAppearance
57 |
58 |
59 |
60 |
--------------------------------------------------------------------------------
/example/ios/AdmobExample/main.m:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) Facebook, Inc. and its affiliates.
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | */
7 |
8 | #import
9 |
10 | #import "AppDelegate.h"
11 |
12 | int main(int argc, char * argv[]) {
13 | @autoreleasepool {
14 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/example/ios/Podfile:
--------------------------------------------------------------------------------
1 | require_relative '../node_modules/react-native/scripts/react_native_pods'
2 | require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
3 |
4 | platform :ios, '11.0'
5 |
6 | target 'AdmobExample' do
7 | config = use_native_modules!
8 |
9 | use_react_native!(
10 | :path => config[:reactNativePath],
11 | # to enable hermes on iOS, change `false` to `true` and then install pods
12 | :hermes_enabled => true
13 | )
14 |
15 | pod 'RNAdMob', :path => '../../'
16 |
17 | # Enables Flipper.
18 | #
19 | # Note that if you have use_frameworks! enabled, Flipper will not work and
20 | # you should disable these next few lines.
21 | use_flipper!()
22 |
23 | post_install do |installer|
24 | react_native_post_install(installer)
25 | __apply_Xcode_12_5_M1_post_install_workaround(installer)
26 | end
27 | end
28 |
--------------------------------------------------------------------------------
/example/metro.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 | const blacklist = require('metro-config/src/defaults/exclusionList');
3 | const escape = require('escape-string-regexp');
4 | const pack = require('../package.json');
5 |
6 | const root = path.resolve(__dirname, '..');
7 |
8 | const modules = [...Object.keys(pack.peerDependencies)];
9 |
10 | module.exports = {
11 | projectRoot: __dirname,
12 | watchFolders: [root],
13 |
14 | // We need to make sure that only one version is loaded for peerDependencies
15 | // So we blacklist them at the root, and alias them to the versions in example's node_modules
16 | resolver: {
17 | blacklistRE: blacklist(
18 | modules.map(
19 | (m) =>
20 | new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`)
21 | )
22 | ),
23 |
24 | extraNodeModules: modules.reduce((acc, name) => {
25 | acc[name] = path.join(__dirname, 'node_modules', name);
26 | return acc;
27 | }, {}),
28 | },
29 |
30 | transformer: {
31 | getTransformOptions: async () => ({
32 | transform: {
33 | experimentalImportSupport: false,
34 | inlineRequires: true,
35 | },
36 | }),
37 | },
38 | };
39 |
--------------------------------------------------------------------------------
/example/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@react-native-admob/admob-example",
3 | "description": "Example app for @react-native-admob/admob",
4 | "version": "0.0.1",
5 | "private": true,
6 | "scripts": {
7 | "android": "react-native run-android",
8 | "ios": "react-native run-ios",
9 | "start": "react-native start",
10 | "lint:js": "eslint --ext '.js,.ts,.tsx' src/ && yarn prettier --check src/"
11 | },
12 | "dependencies": {
13 | "@react-navigation/native": "^6.0.6",
14 | "@react-navigation/native-stack": "^6.2.5",
15 | "react": "17.0.2",
16 | "react-native": "0.67.0",
17 | "react-native-bootsplash": "^3.2.6",
18 | "react-native-safe-area-context": "^3.3.2",
19 | "react-native-screens": "^3.10.2"
20 | },
21 | "devDependencies": {
22 | "@babel/core": "^7.16.7",
23 | "@babel/runtime": "^7.16.7",
24 | "@react-native-community/eslint-config": "^3.0.0",
25 | "@types/react-native": "^0.66.12",
26 | "babel-plugin-module-resolver": "^4.1.0",
27 | "eslint": "^7.32.0",
28 | "metro-react-native-babel-preset": "^0.66.2",
29 | "typescript": "^4.5.4"
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/example/src/App.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | import Navigator from './Navigator';
4 | import PaidProvider from './PaidProvider';
5 |
6 | function App() {
7 | return (
8 |
9 |
10 |
11 | );
12 | }
13 |
14 | export default App;
15 |
--------------------------------------------------------------------------------
/example/src/Navigator.tsx:
--------------------------------------------------------------------------------
1 | import React, { useState } from 'react';
2 | import { AppOpenAdProvider, TestIds } from '@react-native-admob/admob';
3 | import { NavigationContainer } from '@react-navigation/native';
4 | import {
5 | createNativeStackNavigator,
6 | NativeStackNavigationProp,
7 | } from '@react-navigation/native-stack';
8 |
9 | import AppOpenAdExample from './examples/AppOpenAdExample';
10 | import ExamplesScreen from './screens/ExamplesScreen';
11 | import SecondScreen from './screens/SecondScreen';
12 | import { usePaidState } from './PaidProvider';
13 |
14 | const Stack = createNativeStackNavigator();
15 |
16 | export default function Navigator() {
17 | const [splashDismissed, setSplashDismissed] = useState(false);
18 | const { isPaid } = usePaidState();
19 |
20 | return (
21 |
25 |
26 | {splashDismissed ? (
27 |
28 |
29 |
30 |
31 | ) : (
32 | setSplashDismissed(true)}
34 | />
35 | )}
36 |
37 |
38 | );
39 | }
40 |
41 | export type RootStackParamList = {
42 | Examples: undefined;
43 | Second: undefined;
44 | };
45 |
46 | export type RootStackNavigationProps<
47 | T extends keyof RootStackParamList = 'Examples'
48 | > = NativeStackNavigationProp;
49 |
--------------------------------------------------------------------------------
/example/src/PaidProvider.tsx:
--------------------------------------------------------------------------------
1 | import React, { createContext, Dispatch, useContext, useReducer } from 'react';
2 |
3 | interface State {
4 | isPaid: boolean;
5 | }
6 |
7 | type Action = { type: 'TOGGLE_PAID' };
8 |
9 | const PaidStateContext = createContext({
10 | isPaid: false,
11 | });
12 | const PaidDispatchContext = createContext>(() => null);
13 |
14 | function reducer(state: State, action: Action): State {
15 | switch (action.type) {
16 | case 'TOGGLE_PAID':
17 | return {
18 | isPaid: !state.isPaid,
19 | };
20 | default:
21 | throw new Error('Unhandled action');
22 | }
23 | }
24 |
25 | export default function PaidProvider({
26 | children,
27 | }: {
28 | children: React.ReactNode;
29 | }) {
30 | const [state, dispatch] = useReducer(reducer, {
31 | isPaid: false,
32 | });
33 |
34 | return (
35 |
36 |
37 | {children}
38 |
39 |
40 | );
41 | }
42 |
43 | export function usePaidState() {
44 | const state = useContext(PaidStateContext);
45 | return state;
46 | }
47 |
48 | export function usePaidDispatch() {
49 | const dispatch = useContext(PaidDispatchContext);
50 | return dispatch;
51 | }
52 |
--------------------------------------------------------------------------------
/example/src/components/CountDownModal.tsx:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from 'react';
2 | import { Modal, Pressable, StyleSheet, Text, View } from 'react-native';
3 |
4 | interface CountDownModalProps {
5 | visible: boolean;
6 | onCancel: () => void;
7 | onTimeout: () => void;
8 | }
9 |
10 | const CountDownModal = ({
11 | visible,
12 | onCancel,
13 | onTimeout,
14 | }: CountDownModalProps) => {
15 | const [adTick, setAdTick] = useState(5);
16 | const seconds = Math.max(0, adTick);
17 |
18 | useEffect(() => {
19 | setAdTick(5);
20 | const interval = setInterval(() => {
21 | setAdTick((prev) => prev - 1);
22 | }, 1000);
23 | return () => clearInterval(interval);
24 | }, [visible]);
25 |
26 | useEffect(() => {
27 | if (adTick === 0) {
28 | onTimeout();
29 | }
30 | }, [adTick, onTimeout]);
31 |
32 | return (
33 |
39 |
40 |
41 |
42 | Watch this video and earn reward.
43 |
44 | Ad starts in {seconds} seconds
45 |
49 | No Thanks
50 |
51 |
52 |
53 |
54 | );
55 | };
56 |
57 | const styles = StyleSheet.create({
58 | centeredView: {
59 | alignItems: 'center',
60 | flex: 1,
61 | justifyContent: 'center',
62 | },
63 | modalView: {
64 | alignItems: 'center',
65 | backgroundColor: 'white',
66 | borderRadius: 20,
67 | elevation: 5,
68 | margin: 20,
69 | padding: 35,
70 | shadowColor: '#000',
71 | shadowOffset: {
72 | width: 0,
73 | height: 2,
74 | },
75 | shadowOpacity: 0.25,
76 | shadowRadius: 4,
77 | },
78 | button: {
79 | borderRadius: 20,
80 | elevation: 2,
81 | padding: 10,
82 | },
83 | buttonClose: {
84 | backgroundColor: '#2196F3',
85 | },
86 | textStyle: {
87 | color: 'white',
88 | fontWeight: 'bold',
89 | textAlign: 'center',
90 | },
91 | modalText: {
92 | marginBottom: 15,
93 | textAlign: 'center',
94 | },
95 | });
96 |
97 | export default CountDownModal;
98 |
--------------------------------------------------------------------------------
/example/src/components/ExampleGroup.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { StyleProp, StyleSheet, Text, View, ViewStyle } from 'react-native';
3 |
4 | interface ExampleGroupProps {
5 | style?: StyleProp;
6 | title: string;
7 | children: React.ReactNode;
8 | }
9 |
10 | const ExampleGroup = ({
11 | style,
12 | title,
13 | children,
14 | ...props
15 | }: ExampleGroupProps) => (
16 |
17 | {title}
18 | {children}
19 |
20 | );
21 |
22 | const styles = StyleSheet.create({
23 | example: {
24 | paddingVertical: 10,
25 | },
26 | title: {
27 | fontSize: 20,
28 | margin: 10,
29 | },
30 | });
31 |
32 | export default ExampleGroup;
33 |
--------------------------------------------------------------------------------
/example/src/examples/AppOpenAdExample.tsx:
--------------------------------------------------------------------------------
1 | import React, { useEffect, useState } from 'react';
2 | import { View } from 'react-native';
3 | import RNBootSplash from 'react-native-bootsplash';
4 | import { useAppOpenAd } from '@react-native-admob/admob';
5 |
6 | import { usePaidState } from '../PaidProvider';
7 |
8 | interface AppOpenAdExampleProps {
9 | onSplashDismissed: () => void;
10 | }
11 |
12 | const AppOpenAdExample = ({ onSplashDismissed }: AppOpenAdExampleProps) => {
13 | const [loaded, setLoaded] = useState(false);
14 | const { adDismissed, adLoadError } = useAppOpenAd();
15 | const { isPaid } = usePaidState();
16 |
17 | useEffect(() => {
18 | const load = async () => {
19 | await new Promise((resolve) => setTimeout(resolve, 3000));
20 | setLoaded(true);
21 | };
22 | load();
23 | }, []);
24 |
25 | useEffect(() => {
26 | async function hide() {
27 | await RNBootSplash.hide({ fade: true });
28 | onSplashDismissed();
29 | }
30 | if (loaded && (isPaid || adDismissed || adLoadError)) {
31 | hide();
32 | }
33 | }, [loaded, adDismissed, adLoadError, isPaid, onSplashDismissed]);
34 |
35 | return ;
36 | };
37 |
38 | export default AppOpenAdExample;
39 |
--------------------------------------------------------------------------------
/example/src/examples/BannerAdExample.tsx:
--------------------------------------------------------------------------------
1 | import React, { useRef } from 'react';
2 | import { Button, Text } from 'react-native';
3 | import {
4 | BannerAd,
5 | BannerAdSize,
6 | GAMBannerAd,
7 | TestIds,
8 | } from '@react-native-admob/admob';
9 |
10 | import ExampleGroup from '../components/ExampleGroup';
11 | import { usePaidState } from '../PaidProvider';
12 |
13 | const UNIT_ID_GAM_BANNER = '/6499/example/banner';
14 |
15 | const AdSpace = ({
16 | isPaid,
17 | children,
18 | }: {
19 | isPaid: boolean;
20 | children: React.ReactNode;
21 | }) => (isPaid ? Ad was removed : <>{children}>);
22 |
23 | const BannerAdExample = () => {
24 | const bannerRef = useRef(null);
25 | const adaptiveBannerRef = useRef(null);
26 | const gamBannerRef = useRef(null);
27 | const { isPaid } = usePaidState();
28 |
29 | return (
30 | <>
31 |
32 |
33 | console.log('Banner Ad loaded!')}
37 | ref={bannerRef}
38 | />
39 |
41 |
42 |
43 |
44 |
52 |
57 |
58 |
59 |
60 | {
63 | console.log(size);
64 | }}
65 | unitId={UNIT_ID_GAM_BANNER}
66 | ref={gamBannerRef}
67 | />
68 |
73 |
74 | >
75 | );
76 | };
77 |
78 | export default BannerAdExample;
79 |
--------------------------------------------------------------------------------
/example/src/examples/FullScreenAdExamples/ClassApiExample.tsx:
--------------------------------------------------------------------------------
1 | /* eslint-disable react/no-did-update-set-state */
2 | import React from 'react';
3 | import { Button } from 'react-native';
4 | import { InterstitialAd, TestIds } from '@react-native-admob/admob';
5 | import { useNavigation } from '@react-navigation/native';
6 |
7 | import ExampleGroup from '../../components/ExampleGroup';
8 | import { RootStackNavigationProps } from '../../Navigator';
9 | import { usePaidState } from '../../PaidProvider';
10 |
11 | interface State {
12 | adLoaded: boolean;
13 | interstitialAd: InterstitialAd | null;
14 | }
15 |
16 | interface Props {
17 | navigation: RootStackNavigationProps<'Examples'>;
18 | isPaid: boolean;
19 | }
20 |
21 | class ClassApiExample extends React.Component {
22 | state: State = {
23 | adLoaded: false,
24 | interstitialAd: this.props.isPaid ? null : this.createAd(),
25 | };
26 | createAd() {
27 | const ad = InterstitialAd.createAd(TestIds.INTERSTITIAL_VIDEO, {
28 | loadOnDismissed: true,
29 | requestOptions: {
30 | requestNonPersonalizedAdsOnly: true,
31 | },
32 | });
33 | ad.addEventListener('adLoaded', () => {
34 | this.setState({ adLoaded: true });
35 | });
36 | ad.addEventListener('adDismissed', () => {
37 | this.navigateToSecondScreen();
38 | });
39 | return ad;
40 | }
41 |
42 | navigateToSecondScreen = () => this.props.navigation.navigate('Second');
43 |
44 | componentDidUpdate(prevProps: Props, prevState: State) {
45 | if (this.props.isPaid !== prevProps.isPaid) {
46 | this.setState({
47 | interstitialAd: this.props.isPaid ? null : this.createAd(),
48 | });
49 | }
50 | if (this.state.interstitialAd !== prevState.interstitialAd) {
51 | this.setState({ adLoaded: false });
52 | prevState.interstitialAd?.destroy();
53 | }
54 | }
55 |
56 | componentWillUnmount() {
57 | this.state.interstitialAd?.destroy();
58 | }
59 |
60 | render() {
61 | return (
62 |
63 |
74 | );
75 | }
76 | }
77 |
78 | export default function () {
79 | const navigation = useNavigation>();
80 | const { isPaid } = usePaidState();
81 | return ;
82 | }
83 |
--------------------------------------------------------------------------------
/example/src/examples/FullScreenAdExamples/HookApiExample.tsx:
--------------------------------------------------------------------------------
1 | import React, { useCallback, useEffect, useState } from 'react';
2 | import { Button } from 'react-native';
3 | import {
4 | FullScreenAdOptions,
5 | TestIds,
6 | useRewardedInterstitialAd,
7 | } from '@react-native-admob/admob';
8 | import { useNavigation } from '@react-navigation/core';
9 |
10 | import CountDownModal from '../../components/CountDownModal';
11 | import ExampleGroup from '../../components/ExampleGroup';
12 | import { RootStackNavigationProps } from '../../Navigator';
13 |
14 | const hookOptions: FullScreenAdOptions = {
15 | loadOnDismissed: true,
16 | requestOptions: {
17 | requestNonPersonalizedAdsOnly: true,
18 | serverSideVerificationOptions: {
19 | userId: '123',
20 | },
21 | },
22 | };
23 |
24 | const HookApiExample = () => {
25 | const [modalVisible, setModalVisible] = useState(false);
26 | const { adLoaded, adDismissed, reward, show, adLoadError } =
27 | useRewardedInterstitialAd(TestIds.REWARDED_INTERSTITIAL, hookOptions);
28 | const navigation = useNavigation>();
29 |
30 | const navigateToSecondScreen = useCallback(
31 | () => navigation.navigate('Second'),
32 | [navigation]
33 | );
34 |
35 | useEffect(() => {
36 | if (adDismissed) {
37 | setModalVisible(false);
38 | navigateToSecondScreen();
39 | }
40 | }, [adDismissed, navigateToSecondScreen]);
41 |
42 | useEffect(() => {
43 | if (reward) {
44 | console.log('Reward earned from Rewarded Interstitial Ad: ');
45 | console.log(reward);
46 | }
47 | }, [reward]);
48 |
49 | useEffect(() => {
50 | if (adLoadError) {
51 | const { code, message } = adLoadError;
52 | console.log(`Ad failed to load with code ${code} - ${message}`);
53 | }
54 | }, [adLoadError]);
55 |
56 | return (
57 | <>
58 |
59 |
70 | {modalVisible && (
71 | {
74 | setModalVisible(false);
75 | navigateToSecondScreen();
76 | }}
77 | onTimeout={show}
78 | />
79 | )}
80 | >
81 | );
82 | };
83 |
84 | export default HookApiExample;
85 |
--------------------------------------------------------------------------------
/example/src/screens/ExamplesScreen.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Button, SafeAreaView, ScrollView } from 'react-native';
3 |
4 | import BannerAdExample from '../examples/BannerAdExample';
5 | import ClassApiExample from '../examples/FullScreenAdExamples/ClassApiExample';
6 | import HookApiExample from '../examples/FullScreenAdExamples/HookApiExample';
7 | import { usePaidDispatch, usePaidState } from '../PaidProvider';
8 |
9 | const ExamplesScreen = () => {
10 | const { isPaid } = usePaidState();
11 | const dispatch = usePaidDispatch();
12 | return (
13 |
14 |
15 |
16 |
17 |
18 |
23 |
24 | );
25 | };
26 |
27 | export default ExamplesScreen;
28 |
--------------------------------------------------------------------------------
/example/src/screens/SecondScreen.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { Text, View } from 'react-native';
3 |
4 | const SecondScreen = () => {
5 | return (
6 |
7 | This is a second screen.
8 |
9 | );
10 | };
11 |
12 | export default SecondScreen;
13 |
--------------------------------------------------------------------------------
/example/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../tsconfig.json",
3 | "compilerOptions": {
4 | "baseUrl": ".",
5 | "paths": {
6 | "@react-native-admob/admob": [
7 | "../src"
8 | ]
9 | },
10 | },
11 | "include": [
12 | "index.js",
13 | "src/**/*",
14 | ]
15 | }
16 |
--------------------------------------------------------------------------------
/ios/RNAdMob.xcodeproj/xcshareddata/xcschemes/RNAdMob.xcscheme:
--------------------------------------------------------------------------------
1 |
2 |
5 |
8 |
9 |
15 |
21 |
22 |
23 |
24 |
25 |
30 |
31 |
32 |
33 |
43 |
44 |
50 |
51 |
57 |
58 |
59 |
60 |
62 |
63 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/ios/RNAdMob/Ads/Banner/RNAdMobBannerView.h:
--------------------------------------------------------------------------------
1 | #import
2 | #import
3 | #import
4 |
5 | @import GoogleMobileAds;
6 |
7 | @class RCTEventDispatcher;
8 |
9 | @interface RNAdMobBannerView : UIView
10 |
11 | @property GAMBannerView *bannerView;
12 |
13 | @property (nonatomic, copy) NSString *unitId;
14 | @property (nonatomic, copy) NSString *size;
15 | @property (nonatomic, copy) NSArray *sizes;
16 | @property (nonatomic, copy) NSDictionary *requestOptions;
17 |
18 | @property (nonatomic, copy) RCTDirectEventBlock onSizeChange;
19 | @property (nonatomic, copy) RCTDirectEventBlock onAdLoaded;
20 | @property (nonatomic, copy) RCTDirectEventBlock onAdFailedToLoad;
21 | @property (nonatomic, copy) RCTDirectEventBlock onAdOpened;
22 | @property (nonatomic, copy) RCTDirectEventBlock onAdClosed;
23 |
24 | @property (nonatomic, copy) RCTDirectEventBlock onAppEvent;
25 |
26 | - (void)requestAd;
27 |
28 | @end
29 |
--------------------------------------------------------------------------------
/ios/RNAdMob/Ads/Banner/RNAdMobBannerView.m:
--------------------------------------------------------------------------------
1 | #import "RNAdMobBannerView.h"
2 | #import "RNAdMobCommon.h"
3 |
4 | @implementation RNAdMobBannerView
5 |
6 | - (void)setUnitId:(NSString *)unitId {
7 | _unitId = unitId;
8 | [self requestAd];
9 | }
10 |
11 | - (void)setSize:(NSString *)size {
12 | _size = size;
13 | [self requestAd];
14 | }
15 |
16 | - (void)setSizes:(NSArray *)sizes
17 | {
18 | _sizes = sizes;
19 | [self requestAd];
20 | }
21 |
22 | - (void)setRequestOptions:(NSDictionary *)requestOptions
23 | {
24 | _requestOptions = requestOptions;
25 | [self requestAd];
26 | }
27 |
28 | - (void)requestAd
29 | {
30 | if (_unitId == nil || (_size == nil && _sizes == nil) || _requestOptions == nil) {
31 | return;
32 | }
33 | GADAdSize size = [RNAdMobCommon stringToAdSize:_size ? _size : _sizes[0]];
34 | if (!_bannerView) {
35 | _bannerView = [[GAMBannerView alloc] initWithAdSize:size];
36 | _bannerView.delegate = self;
37 | _bannerView.appEventDelegate = self;
38 | _bannerView.adSizeDelegate = self;
39 | _bannerView.rootViewController = RCTPresentedViewController();
40 | [self addSubview:_bannerView];
41 | }
42 | _bannerView.adUnitID = _unitId;
43 | _bannerView.adSize = size;
44 | if (_sizes) {
45 | if ([_unitId hasPrefix:@"/"]) {
46 | _bannerView.validAdSizes = [RNAdMobCommon stringsToValues:_sizes];
47 | } else {
48 | RCTLogError(@"Trying to set sizes in non Ad Manager unit Id");
49 | }
50 | }
51 |
52 | GAMRequest *request = [RNAdMobCommon buildAdRequest:_requestOptions];
53 | [_bannerView loadRequest:request];
54 | }
55 |
56 | # pragma mark GADBannerViewDelegate
57 |
58 | /// Tells the delegate an ad request loaded an ad.
59 | - (void)bannerViewDidReceiveAd:(GAMBannerView *)bannerView
60 | {
61 | _onSizeChange(@{
62 | @"width": @(_bannerView.bounds.size.width),
63 | @"height": @(_bannerView.bounds.size.height),
64 | });
65 |
66 | if (_onAdLoaded) {
67 | _onAdLoaded(nil);
68 | }
69 | }
70 |
71 | /// Tells the delegate an ad request failed.
72 | - (void)bannerView:(__unused GAMBannerView *)bannerView
73 | didFailToReceiveAdWithError:(NSError *)error
74 | {
75 | if (_onAdFailedToLoad) {
76 | NSDictionary *jsError = RCTJSErrorFromCodeMessageAndNSError(@"E_AD_LOAD_FAILED", error.localizedDescription, error);
77 | _onAdFailedToLoad(jsError);
78 | }
79 | }
80 |
81 | /// Tells the delegate that a full screen view will be presented in response
82 | /// to the user clicking on an ad.
83 | - (void)bannerViewWillPresentScreen:(__unused GAMBannerView *)bannerView
84 | {
85 | if (_onAdOpened) {
86 | _onAdOpened(nil);
87 | }
88 | }
89 |
90 | /// Tells the delegate that the full screen view will be dismissed.
91 | - (void)bannerViewDidDismissScreen:(__unused GAMBannerView *)bannerView
92 | {
93 | if (_onAdClosed) {
94 | _onAdClosed(nil);
95 | }
96 | }
97 |
98 | - (void)adView:(__unused GAMBannerView *)bannerView didReceiveAppEvent:(NSString *)name withInfo:(NSString *)info
99 | {
100 | if (_onAppEvent) {
101 | _onAppEvent(@{
102 | @"name": name,
103 | @"info": info
104 | });
105 | }
106 | }
107 |
108 | - (void)adView:(GAMBannerView *)bannerView willChangeAdSizeTo:(GADAdSize)size
109 | {
110 | _onSizeChange(@{
111 | @"width": @(_bannerView.bounds.size.width),
112 | @"height": @(_bannerView.bounds.size.height),
113 | });
114 | }
115 |
116 | @end
117 |
--------------------------------------------------------------------------------
/ios/RNAdMob/Ads/Banner/RNAdMobBannerViewManager.m:
--------------------------------------------------------------------------------
1 | #import "RNAdMobBannerView.h"
2 |
3 | @interface RNAdMobBannerViewManager : RCTViewManager
4 | @end
5 |
6 | @implementation RNAdMobBannerViewManager
7 |
8 | RCT_EXPORT_MODULE();
9 |
10 | - (UIView *)view
11 | {
12 | return [RNAdMobBannerView new];
13 | }
14 |
15 | RCT_EXPORT_METHOD(requestAd:(nonnull NSNumber *)reactTag)
16 | {
17 | [self.bridge.uiManager addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary *viewRegistry) {
18 | RNAdMobBannerView *view = viewRegistry[reactTag];
19 | if (![view isKindOfClass:[RNAdMobBannerView class]]) {
20 | RCTLogError(@"Invalid view returned from registry, expecting RNAdMobBannerView, got: %@", view);
21 | } else {
22 | [view requestAd];
23 | }
24 | }];
25 | }
26 |
27 | RCT_EXPORT_VIEW_PROPERTY(size, NSString)
28 | RCT_EXPORT_VIEW_PROPERTY(unitId, NSString)
29 | RCT_EXPORT_VIEW_PROPERTY(sizes, NSArray)
30 | RCT_EXPORT_VIEW_PROPERTY(requestOptions, NSDictionary)
31 |
32 | RCT_EXPORT_VIEW_PROPERTY(onSizeChange, RCTDirectEventBlock)
33 | RCT_EXPORT_VIEW_PROPERTY(onAdLoaded, RCTDirectEventBlock)
34 | RCT_EXPORT_VIEW_PROPERTY(onAdFailedToLoad, RCTDirectEventBlock)
35 | RCT_EXPORT_VIEW_PROPERTY(onAdOpened, RCTDirectEventBlock)
36 | RCT_EXPORT_VIEW_PROPERTY(onAdClosed, RCTDirectEventBlock)
37 |
38 | RCT_EXPORT_VIEW_PROPERTY(onAppEvent, RCTDirectEventBlock)
39 |
40 | @end
41 |
--------------------------------------------------------------------------------
/ios/RNAdMob/Ads/FullScreen/RNAdMobFullScreenAdBridge.m:
--------------------------------------------------------------------------------
1 | #import
2 |
3 | @interface RCT_EXTERN_MODULE(RNAdMobInterstitialAd, NSObject)
4 |
5 | RCT_EXTERN_METHOD(requestAd:(nonnull NSNumber *)requestId unitId:(nonnull NSString *)unitId options:(nonnull NSDictionary *)options resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
6 |
7 | RCT_EXTERN_METHOD(presentAd:(nonnull NSNumber *)requestId resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
8 |
9 | RCT_EXTERN_METHOD(destroyAd:(nonnull NSNumber *)requestId)
10 |
11 | @end
12 |
13 | @interface RCT_EXTERN_MODULE(RNAdMobRewardedAd, NSObject)
14 |
15 | RCT_EXTERN_METHOD(requestAd:(nonnull NSNumber *)requestId unitId:(nonnull NSString *)unitId options:(nonnull NSDictionary *)options resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
16 |
17 | RCT_EXTERN_METHOD(presentAd:(nonnull NSNumber *)requestId resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
18 |
19 | RCT_EXTERN_METHOD(destroyAd:(nonnull NSNumber *)requestId)
20 |
21 | @end
22 |
23 | @interface RCT_EXTERN_MODULE(RNAdMobRewardedInterstitialAd, NSObject)
24 |
25 | RCT_EXTERN_METHOD(requestAd:(nonnull NSNumber *)requestId unitId:(nonnull NSString *)unitId options:(nonnull NSDictionary *)options resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
26 |
27 | RCT_EXTERN_METHOD(presentAd:(nonnull NSNumber *)requestId resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
28 |
29 | RCT_EXTERN_METHOD(destroyAd:(nonnull NSNumber *)requestId)
30 |
31 | @end
32 |
33 | @interface RCT_EXTERN_MODULE(RNAdMobAppOpenAd, NSObject)
34 |
35 | RCT_EXTERN_METHOD(requestAd:(nonnull NSNumber *)requestId unitId:(nonnull NSString *)unitId options:(nonnull NSDictionary *)options resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
36 |
37 | RCT_EXTERN_METHOD(presentAd:(nonnull NSNumber *)requestId resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
38 |
39 | RCT_EXTERN_METHOD(destroyAd:(nonnull NSNumber *)requestId)
40 |
41 | @end
42 |
--------------------------------------------------------------------------------
/ios/RNAdMob/Ads/FullScreen/RNAdMobInterstitial.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 | import GoogleMobileAds
3 |
4 | @objc(RNAdMobInterstitial)
5 | class RNAdMobInterstitial: RNAdMobFullScreenAd {
6 | static let AD_TYPE = "Interstitial"
7 |
8 | override func getAdType() -> String {
9 | return RNAdMobInterstitial.AD_TYPE
10 | }
11 |
12 | override func load(unitId: String, adRequest: GAMRequest, adLoadDelegate: RNAdMobFullScreenAd.AdLoadDelegate, fullScreenContentDelegate: RNAdMobFullScreenAd.FullScreenContentDelegate) {
13 | GAMInterstitialAd.load(withAdManagerAdUnitID: unitId, request: adRequest) {
14 | (ad, error) in
15 | if (error != nil) {
16 | adLoadDelegate.onAdFailedToLoad(error: error!)
17 | return
18 | }
19 | ad!.fullScreenContentDelegate = fullScreenContentDelegate
20 | adLoadDelegate.onAdLoaded(ad: ad!)
21 | }
22 | }
23 |
24 | override func show(ad: GAMInterstitialAd, viewController: UIViewController, requestId: Int) {
25 | ad.present(fromRootViewController: viewController)
26 | }
27 | }
28 |
29 | @objc(RNAdMobInterstitialAd)
30 | class RNAdMobInterstitialAd: NSObject {
31 | static let ad = RNAdMobInterstitial()
32 | @objc static func requiresMainQueueSetup() -> Bool {
33 | return true
34 | }
35 | @objc func requestAd(_ requestId: NSNumber, unitId: String, options: NSDictionary, resolve: RCTPromiseResolveBlock?, reject: RCTPromiseRejectBlock?) {
36 | RNAdMobInterstitialAd.ad.requestAd(requestId.intValue, unitId: unitId, options: options as! Dictionary, resolve: resolve, reject: reject)
37 | }
38 | @objc func presentAd(_ requestId: NSNumber, resolve: RCTPromiseResolveBlock?, reject: RCTPromiseRejectBlock?) {
39 | RNAdMobInterstitialAd.ad.presentAd(requestId.intValue, resolve: resolve, reject: reject)
40 | }
41 | @objc func destroyAd(_ requestId: NSNumber) {
42 | RNAdMobInterstitialAd.ad.destroyAd(requestId.intValue)
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/ios/RNAdMob/Ads/FullScreen/RNAdMobRewarded.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 | import GoogleMobileAds
3 |
4 | class RNAdMobRewarded: RNAdMobFullScreenAd {
5 | static let AD_TYPE = "Rewarded"
6 |
7 | override func getAdType() -> String {
8 | return RNAdMobRewarded.AD_TYPE
9 | }
10 |
11 | override func load(unitId: String, adRequest: GAMRequest, adLoadDelegate: RNAdMobFullScreenAd.AdLoadDelegate, fullScreenContentDelegate: RNAdMobFullScreenAd.FullScreenContentDelegate) {
12 | GADRewardedAd.load(withAdUnitID: unitId, request: adRequest) {
13 | (ad, error) in
14 | if (error != nil) {
15 | adLoadDelegate.onAdFailedToLoad(error: error!)
16 | return
17 | }
18 | ad!.fullScreenContentDelegate = fullScreenContentDelegate
19 | adLoadDelegate.onAdLoaded(ad: ad!)
20 | }
21 | }
22 |
23 | override func show(ad: GADRewardedAd, viewController: UIViewController, requestId: Int) {
24 | ad.present(fromRootViewController: viewController) {
25 | var reward = Dictionary()
26 | reward.updateValue(ad.adReward.amount, forKey: "amount")
27 | reward.updateValue(ad.adReward.type, forKey: "type")
28 | self.sendEvent(eventName: kEventRewarded, requestId: requestId, data: reward)
29 | }
30 | }
31 | }
32 |
33 | @objc(RNAdMobRewardedAd)
34 | class RNAdMobRewardedAd: NSObject {
35 | static let ad = RNAdMobRewarded()
36 | @objc static func requiresMainQueueSetup() -> Bool {
37 | return true
38 | }
39 | @objc func requestAd(_ requestId: NSNumber, unitId: String, options: NSDictionary, resolve: RCTPromiseResolveBlock?, reject: RCTPromiseRejectBlock?) {
40 | RNAdMobRewardedAd.ad.requestAd(requestId.intValue, unitId: unitId, options: options as! Dictionary, resolve: resolve, reject: reject)
41 | }
42 | @objc func presentAd(_ requestId: NSNumber, resolve: RCTPromiseResolveBlock?, reject: RCTPromiseRejectBlock?) {
43 | RNAdMobRewardedAd.ad.presentAd(requestId.intValue, resolve: resolve, reject: reject)
44 | }
45 | @objc func destroyAd(_ requestId: NSNumber) {
46 | RNAdMobRewardedAd.ad.destroyAd(requestId.intValue)
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/ios/RNAdMob/Ads/FullScreen/RNAdMobRewardedInterstitial.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 | import GoogleMobileAds
3 |
4 | @objc(RNAdMobRewardedInterstitial)
5 | class RNAdMobRewardedInterstitial: RNAdMobFullScreenAd {
6 | static let AD_TYPE = "RewardedInterstitial"
7 |
8 | override func getAdType() -> String {
9 | return RNAdMobRewardedInterstitial.AD_TYPE
10 | }
11 |
12 | override func load(unitId: String, adRequest: GAMRequest, adLoadDelegate: RNAdMobFullScreenAd.AdLoadDelegate, fullScreenContentDelegate: RNAdMobFullScreenAd.FullScreenContentDelegate) {
13 | GADRewardedInterstitialAd.load(withAdUnitID: unitId, request: adRequest) {
14 | (ad, error) in
15 | if (error != nil) {
16 | adLoadDelegate.onAdFailedToLoad(error: error!)
17 | return
18 | }
19 | ad!.fullScreenContentDelegate = fullScreenContentDelegate
20 | adLoadDelegate.onAdLoaded(ad: ad!)
21 | }
22 | }
23 |
24 | override func show(ad: GADRewardedInterstitialAd, viewController: UIViewController, requestId: Int) {
25 | ad.present(fromRootViewController: viewController) {
26 | var reward = Dictionary()
27 | reward.updateValue(ad.adReward.amount, forKey: "amount")
28 | reward.updateValue(ad.adReward.type, forKey: "type")
29 | self.sendEvent(eventName: kEventRewarded, requestId: requestId, data: reward)
30 | }
31 | }
32 | }
33 |
34 | @objc(RNAdMobRewardedInterstitialAd)
35 | class RNAdMobRewardedInterstitialAd: NSObject {
36 | static let ad = RNAdMobRewardedInterstitial()
37 | @objc static func requiresMainQueueSetup() -> Bool {
38 | return true
39 | }
40 | @objc func requestAd(_ requestId: NSNumber, unitId: String, options: NSDictionary, resolve: RCTPromiseResolveBlock?, reject: RCTPromiseRejectBlock?) {
41 | RNAdMobRewardedInterstitialAd.ad.requestAd(requestId.intValue, unitId: unitId, options: options as! Dictionary, resolve: resolve, reject: reject)
42 | }
43 | @objc func presentAd(_ requestId: NSNumber, resolve: RCTPromiseResolveBlock?, reject: RCTPromiseRejectBlock?) {
44 | RNAdMobRewardedInterstitialAd.ad.presentAd(requestId.intValue, resolve: resolve, reject: reject)
45 | }
46 | @objc func destroyAd(_ requestId: NSNumber) {
47 | RNAdMobRewardedInterstitialAd.ad.destroyAd(requestId.intValue)
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/ios/RNAdMob/RNAdMob.m:
--------------------------------------------------------------------------------
1 | #import
2 | #import
3 | #if __has_include("")
4 | #import
5 | #endif
6 |
7 | @import GoogleMobileAds;
8 | @import AdSupport;
9 |
10 | @interface RNAdMob : NSObject
11 | @end
12 |
13 | @implementation RNAdMob
14 |
15 | -(id)init{
16 | self = [super init];
17 |
18 | #if __has_include("")
19 | if (@available(iOS 14, *)) {
20 | if ([ATTrackingManager trackingAuthorizationStatus] == ATTrackingManagerAuthorizationStatusAuthorized) {
21 | [FBAdSettings setAdvertiserTrackingEnabled:trackingAuthorizationStatus];
22 | }
23 | }
24 | #endif
25 |
26 | GADMobileAds *ads = [GADMobileAds sharedInstance];
27 | ads.requestConfiguration.testDeviceIdentifiers = @[kGAMSimulatorID];
28 | [ads startWithCompletionHandler:nil];
29 |
30 | return self;
31 | }
32 |
33 | +(BOOL)requiresMainQueueSetup {
34 | return YES;
35 | }
36 |
37 | RCT_EXPORT_MODULE();
38 |
39 | RCT_EXPORT_METHOD(getInitializationStatus:(RCTPromiseResolveBlock) resolve rejecter:(RCTPromiseRejectBlock) reject)
40 | {
41 | GADMobileAds *ads = [GADMobileAds sharedInstance];
42 | GADInitializationStatus *status = [ads initializationStatus];
43 |
44 | if (status == nil) {
45 | reject(@"E_MOBILE_ADS_NOT_INITIALIZED", @"MobileAds SDK is not initialized yet.", nil);
46 | return;
47 | }
48 |
49 | NSDictionary *adapterStatuses = [status adapterStatusesByClassName];
50 | NSMutableArray *adapters = [NSMutableArray array];
51 | for (NSString *adapter in adapterStatuses) {
52 | GADAdapterStatus *adapterStatus = adapterStatuses[adapter];
53 | NSDictionary *dict = @{
54 | @"name":adapter,
55 | @"state":@([@(adapterStatus.state) boolValue]),
56 | @"description":adapterStatus.description
57 | };
58 | [adapters addObject:dict];
59 | }
60 | resolve(adapters);
61 | }
62 |
63 | RCT_EXPORT_METHOD(setRequestConfiguration:(NSDictionary *)config)
64 | {
65 | if ([[config allKeys] containsObject:@"maxAdContentRating"]) {
66 | NSString *rating = [config valueForKey:@"maxAdContentRating"];
67 | if ([rating isEqualToString:@"G"]) {
68 | [[[GADMobileAds sharedInstance] requestConfiguration] setMaxAdContentRating:GADMaxAdContentRatingGeneral];
69 | } else if ([rating isEqualToString:@"PG"]) {
70 | [[[GADMobileAds sharedInstance] requestConfiguration] setMaxAdContentRating:GADMaxAdContentRatingParentalGuidance];
71 | } else if ([rating isEqualToString:@"MA"]) {
72 | [[[GADMobileAds sharedInstance] requestConfiguration] setMaxAdContentRating:GADMaxAdContentRatingMatureAudience];
73 | } else if ([rating isEqualToString:@"T"]) {
74 | [[[GADMobileAds sharedInstance] requestConfiguration] setMaxAdContentRating:GADMaxAdContentRatingTeen];
75 | } else if ([rating isEqualToString:@""]) {
76 | [[[GADMobileAds sharedInstance] requestConfiguration] setMaxAdContentRating:NULL];
77 | }
78 | };
79 |
80 | if ([[config allKeys] containsObject:@"tagForChildDirectedTreatment"]) {
81 | NSNumber *tag = [config valueForKey:@"tagForChildDirectedTreatment"];
82 | [[[GADMobileAds sharedInstance] requestConfiguration] tagForChildDirectedTreatment:tag.boolValue];
83 | };
84 |
85 | if ([[config allKeys] containsObject:@"tagForUnderAgeConsent"]) {
86 | NSNumber *tagC = [config valueForKey:@"tagForUnderAgeConsent"];
87 | [[[GADMobileAds sharedInstance] requestConfiguration] tagForUnderAgeOfConsent:tagC.boolValue];
88 | };
89 |
90 | if ([[config allKeys] containsObject:@"testDeviceIds"]) {
91 | NSMutableArray *testDevices = [config valueForKey:@"testDeviceIds"];
92 | [testDevices addObject:kGAMSimulatorID];
93 | [[[GADMobileAds sharedInstance] requestConfiguration] setTestDeviceIdentifiers:testDevices];
94 | };
95 | }
96 |
97 | RCT_EXPORT_METHOD(isTestDevice:(RCTPromiseResolveBlock)resolve
98 | rejecter:(RCTPromiseRejectBlock)reject) {
99 | NSArray *testDeviceIds = GADMobileAds.sharedInstance.requestConfiguration.testDeviceIdentifiers;
100 | BOOL value = [testDeviceIds containsObject:[[ASIdentifierManager sharedManager] advertisingIdentifier]];
101 | resolve([NSNumber numberWithBool:value]);
102 | }
103 |
104 | @end
105 |
--------------------------------------------------------------------------------
/ios/RNAdMob/RNAdMobAdHolder.swift:
--------------------------------------------------------------------------------
1 | class RNAdMobAdHolder {
2 | private var adArrayQueue = DispatchQueue(label: "RNAdMobAdHolderQueue")
3 | private var adArray = Dictionary()
4 |
5 | func add(requestId: Int, ad: T) {
6 | adArrayQueue.sync {
7 | adArray.updateValue(ad, forKey: requestId)
8 | }
9 | }
10 |
11 | func get(requestId: Int) -> T? {
12 | adArrayQueue.sync {
13 | return adArray[requestId]
14 | }
15 | }
16 |
17 | func remove(requestId: Int) {
18 | adArrayQueue.sync {
19 | adArray.removeValue(forKey: requestId)
20 | }
21 | }
22 |
23 | func clear() {
24 | adArrayQueue.async(flags: .barrier) {[weak self] in
25 | self?.adArray.removeAll()
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/ios/RNAdMob/RNAdMobCommon.h:
--------------------------------------------------------------------------------
1 | #import
2 | #import
3 | #import
4 |
5 | @import GoogleMobileAds;
6 |
7 | @interface RNAdMobCommon : NSObject
8 |
9 | + (GADAdSize)stringToAdSize:(NSString *)value;
10 |
11 | + (NSArray *)stringsToValues:(NSArray *)values;
12 |
13 | + (GAMRequest *)buildAdRequest:(NSDictionary *)requestOptions;
14 |
15 | + (GADServerSideVerificationOptions *)buildServerSideVerificationOptions:(NSDictionary *)requestOptions;
16 |
17 | @end
18 |
--------------------------------------------------------------------------------
/ios/RNAdMob/RNAdMobEvent.h:
--------------------------------------------------------------------------------
1 | #import
2 | #import
3 |
4 | static NSString * _Nonnull const kEventAdLoaded = @"adLoaded";
5 | static NSString * _Nonnull const kEventAdFailedToLoad = @"adFailedToLoad";
6 | static NSString * _Nonnull const kEventAdPresented = @"adPresented";
7 | static NSString * _Nonnull const kEventAdFailedToPresent = @"adFailedToPresent";
8 | static NSString * _Nonnull const kEventAdDismissed = @"adDismissed";
9 | static NSString * _Nonnull const kEventRewarded = @"rewarded";
10 |
11 | @interface RNAdMobEvent : RCTEventEmitter
12 |
13 | @property (nonatomic, assign) BOOL hasListeners;
14 |
15 | + (void)sendEvent:(NSString *_Nonnull)eventName type:(NSString *_Nonnull)type requestId:(NSNumber*_Nonnull) requestId data:(NSDictionary *_Nullable)data;
16 |
17 | @end
18 |
--------------------------------------------------------------------------------
/ios/RNAdMob/RNAdMobEvent.m:
--------------------------------------------------------------------------------
1 | #import "RNAdMobEvent.h"
2 |
3 | @implementation RNAdMobEvent
4 |
5 | + (id)allocWithZone:(NSZone *)zone {
6 | static RNAdMobEvent *sharedInstance = nil;
7 | static dispatch_once_t onceToken;
8 | dispatch_once(&onceToken, ^{
9 | sharedInstance = [super allocWithZone:zone];
10 | });
11 | return sharedInstance;
12 | }
13 |
14 | + (void)sendEvent:(NSString *)eventName type:(NSString *)type requestId:(NSNumber*) requestId data:(NSDictionary *)data {
15 | RNAdMobEvent* eventModule = [RNAdMobEvent allocWithZone: nil];
16 | if (!eventModule.hasListeners) {
17 | return;
18 | }
19 | if (data) {
20 | [eventModule sendEventWithName:eventName body:@{
21 | @"type": type,
22 | @"requestId": requestId,
23 | @"data": data
24 | }];
25 | } else {
26 | [eventModule sendEventWithName:eventName body:@{
27 | @"type": type,
28 | @"requestId": requestId
29 | }];
30 | }
31 |
32 | }
33 |
34 | RCT_EXPORT_MODULE();
35 |
36 | - (NSArray *)supportedEvents
37 | {
38 | return @[
39 | kEventAdPresented,
40 | kEventAdFailedToPresent,
41 | kEventAdDismissed,
42 | kEventRewarded,
43 | kEventAdLoaded,
44 | kEventAdFailedToLoad
45 | ];
46 | }
47 |
48 | - (void)startObserving
49 | {
50 | _hasListeners = YES;
51 | }
52 |
53 | - (void)stopObserving
54 | {
55 | _hasListeners = NO;
56 | }
57 |
58 | @end
59 |
--------------------------------------------------------------------------------
/ios/RNAdMob/RNAdMobPromiseHolder.swift:
--------------------------------------------------------------------------------
1 | class RNAdMobPromiseHolder {
2 | private var resolveArray = Dictionary()
3 | private var rejectArray = Dictionary()
4 |
5 | func add(requestId: Int, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
6 | resolveArray.updateValue(resolve, forKey: requestId)
7 | rejectArray.updateValue(reject, forKey: requestId)
8 | }
9 |
10 | func clear() {
11 | resolveArray.removeAll()
12 | rejectArray.removeAll()
13 | }
14 |
15 | func resolve(requestId: Int) {
16 | let resolveBlock = resolveArray[requestId]
17 | if (resolveBlock != nil) {
18 | resolveBlock!(nil)
19 | }
20 | resolveArray.removeValue(forKey: requestId)
21 | rejectArray.removeValue(forKey: requestId)
22 | }
23 |
24 | func reject(requestId: Int, errorData: Dictionary) {
25 | let rejectBlock = rejectArray[requestId]
26 | if (rejectBlock != nil) {
27 | let error = NSError.init(domain: "com.rnadmob.admob", code: 0, userInfo: errorData)
28 | rejectBlock!(kEventAdFailedToPresent, "Error occurred while showing ad.", error)
29 | }
30 | resolveArray.removeValue(forKey: requestId)
31 | rejectArray.removeValue(forKey: requestId)
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@react-native-admob/admob",
3 | "version": "2.0.1",
4 | "description": "Admob for React Native with powerful hooks and components",
5 | "main": "lib/commonjs/index.js",
6 | "module": "lib/module/index.js",
7 | "types": "lib/typescript/index.d.ts",
8 | "react-native": "src/index.ts",
9 | "files": [
10 | "src",
11 | "lib",
12 | "!**/__tests__",
13 | "!**/__fixtures__",
14 | "!**/__mocks__",
15 | "android",
16 | "ios",
17 | "RNAdMob.podspec",
18 | "!android/build",
19 | "!ios/build"
20 | ],
21 | "scripts": {
22 | "lint:js": "eslint --ext '.js,.ts,.tsx' src/ && yarn prettier --check src/",
23 | "release": "release-it",
24 | "type:check": "yarn tsc --noEmit",
25 | "prepare": "bob build"
26 | },
27 | "keywords": [
28 | "react-native",
29 | "ios",
30 | "android",
31 | "admob"
32 | ],
33 | "repository": {
34 | "type": "git",
35 | "url": "git+https://github.com/react-native-admob/admob.git"
36 | },
37 | "author": "Jay Kim (https://github.com/wjaykim)",
38 | "license": "MIT",
39 | "readmeFilename": "README.md",
40 | "bugs": {
41 | "url": "https://github.com/react-native-admob/admob/issues"
42 | },
43 | "homepage": "https://github.com/react-native-admob/admob#readme",
44 | "publishConfig": {
45 | "access": "public"
46 | },
47 | "peerDependencies": {
48 | "react": "*",
49 | "react-native": "*"
50 | },
51 | "devDependencies": {
52 | "@babel/core": "^7.16.7",
53 | "@babel/eslint-parser": "^7.16.5",
54 | "@react-native-community/eslint-config": "^3.0.0",
55 | "@release-it/conventional-changelog": "^4.1.0",
56 | "@types/react-native": "^0.66.12",
57 | "eslint": "^7.32.0",
58 | "eslint-plugin-import": "^2.25.4",
59 | "eslint-plugin-prettier": "^4.0.0",
60 | "eslint-plugin-simple-import-sort": "^7.0.0",
61 | "eslint-plugin-unused-imports": "^1.1.5",
62 | "husky": "^7.0.4",
63 | "lint-staged": "^12.2.0",
64 | "prettier": "^2.5.1",
65 | "react": "17.0.2",
66 | "react-native": "0.67.0",
67 | "react-native-builder-bob": "^0.18.2",
68 | "release-it": "^14.12.3",
69 | "typescript": "^4.5.4"
70 | },
71 | "lint-staged": {
72 | "*.(js|ts|tsx)": [
73 | "eslint --ext '.js,.ts,.tsx' src/",
74 | "prettier --write"
75 | ]
76 | },
77 | "release-it": {
78 | "npm": {
79 | "publish": true
80 | },
81 | "github": {
82 | "release": true,
83 | "releaseName": "Release ${version}",
84 | "web": true
85 | },
86 | "plugins": {
87 | "@release-it/conventional-changelog": {
88 | "preset": {
89 | "name": "conventionalcommits",
90 | "types": [
91 | {
92 | "type": "feat",
93 | "section": "💡 Features"
94 | },
95 | {
96 | "type": "fix",
97 | "section": "🐛 Bug Fixes"
98 | },
99 | {
100 | "type": "docs",
101 | "section": "📓 Docs improvements"
102 | }
103 | ]
104 | },
105 | "parserOpts": {
106 | "noteKeywords": [
107 | "🚨 Breaking changes"
108 | ]
109 | }
110 | }
111 | }
112 | },
113 | "react-native-builder-bob": {
114 | "source": "src",
115 | "output": "lib",
116 | "targets": [
117 | "commonjs",
118 | "module",
119 | "typescript"
120 | ]
121 | },
122 | "eslintIgnore": [
123 | "node_modules/",
124 | "lib/"
125 | ],
126 | "dependencies": {
127 | "use-deep-compare-effect": "^1.8.1"
128 | }
129 | }
130 |
--------------------------------------------------------------------------------
/src/AdError.ts:
--------------------------------------------------------------------------------
1 | export default class AdError extends Error {
2 | name = 'AdError';
3 | /**
4 | * AdError
5 | * @param message - The error description message.
6 | * @param code - The error code.
7 | * @link https://support.google.com/admob/answer/9905175
8 | */
9 | constructor(public readonly message: string, public readonly code?: number) {
10 | super();
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/AdMob.ts:
--------------------------------------------------------------------------------
1 | import { NativeModules } from 'react-native';
2 |
3 | import { InitializationStatus, RequestConfiguration } from './types';
4 |
5 | const RNAdMobAdManager = NativeModules.RNAdMob;
6 |
7 | /**
8 | * Initializes Mobile Ads SDK.
9 | * @deprecated since version 1.2.0, SDK is initialized automatically. Use `getInitializationStatus` instead if you need to get adapters' initialization status.
10 | * @returns Promise of each mediation adapter's initialization status
11 | */
12 | async function initialize(): Promise {
13 | return getInitializationStatus();
14 | }
15 |
16 | /**
17 | * Get Mobile Ads SDK initialization status.
18 | * @returns Promise of each mediation adapter's initialization status
19 | */
20 | async function getInitializationStatus(): Promise {
21 | return RNAdMobAdManager.getInitializationStatus();
22 | }
23 |
24 | /**
25 | * Sets ads request configuration to be applied globally.
26 | * @param config `RequestConfiguration` object
27 | */
28 | function setRequestConfiguration(config?: RequestConfiguration) {
29 | RNAdMobAdManager.setRequestConfiguration(config || {});
30 | }
31 |
32 | /**
33 | * Checks if the current device is registered as a test device to show test ads.
34 | * @returns Promise of boolean weather current device is a test device
35 | */
36 | async function isTestDevice(): Promise {
37 | return RNAdMobAdManager.isTestDevice();
38 | }
39 |
40 | export default {
41 | initialize,
42 | getInitializationStatus,
43 | setRequestConfiguration,
44 | isTestDevice,
45 | };
46 |
--------------------------------------------------------------------------------
/src/ads/AppOpenAdContext.ts:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 |
3 | import { AppOpenAdOptions } from '../types';
4 |
5 | import { AppOpenAd } from './fullscreen';
6 |
7 | interface AppOpenAdContextState {
8 | unitId: string | null;
9 | options?: AppOpenAdOptions;
10 | appOpenAd: AppOpenAd | null;
11 | }
12 |
13 | /**
14 | * Context which holds the App Open Ad.
15 | */
16 | const AppOpenAdContext = React.createContext(
17 | undefined
18 | );
19 |
20 | export default AppOpenAdContext;
21 |
--------------------------------------------------------------------------------
/src/ads/AppOpenAdProvider.tsx:
--------------------------------------------------------------------------------
1 | import React, { useState } from 'react';
2 | import useDeepCompareEffect from 'use-deep-compare-effect';
3 |
4 | import { AppOpenAdOptions } from '../types';
5 |
6 | import AppOpenAdContext from './AppOpenAdContext';
7 | import { AppOpenAd } from './fullscreen';
8 |
9 | export interface AppOpenAdProviderProps {
10 | unitId: string | null;
11 | options?: AppOpenAdOptions;
12 | children: React.ReactNode;
13 | }
14 |
15 | const AppOpenAdProvider = ({
16 | unitId,
17 | options = {},
18 | children,
19 | }: AppOpenAdProviderProps) => {
20 | const [appOpenAd, setAppOpenAd] = useState(null);
21 |
22 | useDeepCompareEffect(() => {
23 | if (AppOpenAd.getAd()) {
24 | AppOpenAd.destroy();
25 | }
26 | setAppOpenAd(unitId ? AppOpenAd.createAd(unitId, options) : null);
27 | }, [unitId, options]);
28 |
29 | return (
30 |
31 | {children}
32 |
33 | );
34 | };
35 |
36 | export default AppOpenAdProvider;
37 |
--------------------------------------------------------------------------------
/src/ads/banner/BannerAd.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | import { BannerAdProps } from '../../types';
4 |
5 | import BaseAd, { RNAdMobBannerView } from './BaseAd';
6 |
7 | class BannerAd extends BaseAd {
8 | render() {
9 | return (
10 | {
20 | //@ts-expect-error
21 | this.bannerRef = el;
22 | }}
23 | />
24 | );
25 | }
26 | }
27 |
28 | export default BannerAd;
29 |
--------------------------------------------------------------------------------
/src/ads/banner/BaseAd.tsx:
--------------------------------------------------------------------------------
1 | import { Component, createRef } from 'react';
2 | import {
3 | findNodeHandle,
4 | requireNativeComponent,
5 | StyleProp,
6 | UIManager,
7 | ViewStyle,
8 | } from 'react-native';
9 |
10 | import { BannerAdProps, GAMBannerAdProps } from '../../types';
11 |
12 | interface BannerAdState {
13 | style: StyleProp;
14 | }
15 |
16 | export const RNAdMobBannerView =
17 | requireNativeComponent('RNAdMobBannerView');
18 |
19 | abstract class BaseAd<
20 | T extends BannerAdProps | GAMBannerAdProps
21 | > extends Component {
22 | state: BannerAdState = {
23 | style: { width: 0, height: 0 },
24 | };
25 | bannerRef = createRef();
26 |
27 | loadAd() {
28 | UIManager.dispatchViewManagerCommand(
29 | //@ts-expect-error
30 | findNodeHandle(this.bannerRef),
31 | 'requestAd',
32 | undefined
33 | );
34 | }
35 |
36 | protected handleSizeChange(event: any) {
37 | const { height, width } = event.nativeEvent;
38 | this.setState({ style: { width, height } });
39 | if (this.props.onSizeChange) {
40 | this.props.onSizeChange({ width, height });
41 | }
42 | }
43 |
44 | protected handleOnAdLoaded() {
45 | if (this.props.onAdLoaded) {
46 | this.props.onAdLoaded();
47 | }
48 | }
49 |
50 | protected handleOnAdFailedToLoad(event: any) {
51 | if (this.props.onAdFailedToLoad) {
52 | this.props.onAdFailedToLoad(event.nativeEvent);
53 | }
54 | }
55 |
56 | protected handleOnAdOpened() {
57 | if (this.props.onAdOpened) {
58 | this.props.onAdOpened();
59 | }
60 | }
61 |
62 | protected handleOnAdClosed() {
63 | if (this.props.onAdClosed) {
64 | this.props.onAdClosed();
65 | }
66 | }
67 | }
68 |
69 | export default BaseAd;
70 |
--------------------------------------------------------------------------------
/src/ads/banner/GAMBannerAd.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | import { GAMBannerAdProps } from '../../types';
4 |
5 | import BaseAd, { RNAdMobBannerView } from './BaseAd';
6 |
7 | class GAMBannerAd extends BaseAd {
8 | protected handleOnAppEvent(event: any) {
9 | const { name, info } = event.nativeEvent;
10 | if (this.props.onAppEvent) {
11 | this.props.onAppEvent(name, info);
12 | }
13 | }
14 |
15 | render() {
16 | return (
17 | {
28 | //@ts-expect-error
29 | this.bannerRef = el;
30 | }}
31 | />
32 | );
33 | }
34 | }
35 |
36 | export default GAMBannerAd;
37 |
--------------------------------------------------------------------------------
/src/ads/banner/index.ts:
--------------------------------------------------------------------------------
1 | export { default as BannerAd } from './BannerAd';
2 | export { default as GAMBannerAd } from './GAMBannerAd';
3 |
--------------------------------------------------------------------------------
/src/ads/fullscreen/AppOpenAd.ts:
--------------------------------------------------------------------------------
1 | import {
2 | AppOpenAdOptions,
3 | FullScreenAdEvent,
4 | FullScreenAdHandlerType,
5 | RequestOptions,
6 | } from '../../types';
7 |
8 | import FullScreenAd from './FullScreenAd';
9 |
10 | const defaultOptions: AppOpenAdOptions = {
11 | showOnColdStart: false,
12 | showOnAppForeground: true,
13 | loadOnDismissed: true,
14 | requestOptions: {},
15 | };
16 |
17 | let _appOpenRequest = 0;
18 |
19 | export default class AppOpenAd extends FullScreenAd {
20 | private constructor(
21 | requestId: number,
22 | unitId: string,
23 | options: AppOpenAdOptions
24 | ) {
25 | super('AppOpen', requestId, unitId, options);
26 | }
27 |
28 | private static sharedInstance: AppOpenAd | null = null;
29 |
30 | private static checkInstance() {
31 | if (!this.sharedInstance) {
32 | throw new Error('AppOpenAd is not created.');
33 | }
34 | }
35 |
36 | /**
37 | * Creates a AppOpenAd instance. Ad is loaded automatically after created and after dismissed.
38 | * @param unitId The Ad Unit ID for the App Open Ad. You can find this on your Google AdMob dashboard.
39 | * @param options Optional AppOpenAdOptions object.
40 | */
41 | static createAd(unitId: string, options?: AppOpenAdOptions) {
42 | const _options = { ...defaultOptions, ...options };
43 |
44 | this.sharedInstance?.destroy();
45 |
46 | const requestId = _appOpenRequest++;
47 | this.sharedInstance = new AppOpenAd(requestId, unitId, _options);
48 | return this.sharedInstance;
49 | }
50 |
51 | /**
52 | * Returns loaded App Open Ad instance.
53 | */
54 | static getAd() {
55 | return this.sharedInstance;
56 | }
57 |
58 | /**
59 | * Loads a new App Open ad.
60 | * @param requestOptions Optional RequestOptions used to load the ad.
61 | */
62 | static load(requestOptions?: RequestOptions) {
63 | this.checkInstance();
64 | return this.sharedInstance!.load(requestOptions);
65 | }
66 |
67 | /**
68 | * Shows loaded App Open Ad.
69 | */
70 | static show() {
71 | this.checkInstance();
72 | return this.sharedInstance!.show();
73 | }
74 |
75 | /**
76 | * Destroys the App Open Ad.
77 | */
78 | static destroy() {
79 | this.checkInstance();
80 | this.sharedInstance!.destroy();
81 | this.sharedInstance = null;
82 | }
83 |
84 | /**
85 | * Sets RequestOptions for this Ad instance.
86 | * @param requestOptions RequestOptions used to load the ad.
87 | */
88 | static setRequestOptions(requestOptions?: RequestOptions) {
89 | this.checkInstance();
90 | return this.sharedInstance!.setRequestOptions(requestOptions);
91 | }
92 |
93 | /**
94 | * Adds an event handler for an ad event.
95 | * @param event Event name
96 | * @param handler Event handler
97 | */
98 | static addEventListener(
99 | event: FullScreenAdEvent,
100 | handler: FullScreenAdHandlerType
101 | ) {
102 | this.checkInstance();
103 | return this.sharedInstance!.addEventListener(event, handler);
104 | }
105 |
106 | /**
107 | * Removes all registered event handlers for this ad.
108 | */
109 | static removeAllListeners() {
110 | this.checkInstance();
111 | return this.sharedInstance!.removeAllListeners();
112 | }
113 | }
114 |
--------------------------------------------------------------------------------
/src/ads/fullscreen/InterstitialAd.ts:
--------------------------------------------------------------------------------
1 | import { FullScreenAdOptions } from '../../types';
2 |
3 | import FullScreenAd from './FullScreenAd';
4 |
5 | let _interstitialRequest = 0;
6 |
7 | export default class InterstitialAd extends FullScreenAd {
8 | private constructor(
9 | requestId: number,
10 | unitId: string,
11 | options?: FullScreenAdOptions
12 | ) {
13 | super('Interstitial', requestId, unitId, options);
14 | }
15 |
16 | /**
17 | * Creates a new InterstitialAd instance.
18 | * @param unitId The Ad Unit ID for the Interstitial Ad. You can find this on your Google AdMob dashboard.
19 | * @param options Optional FullScreenAdOptions for this ad.
20 | */
21 | static createAd(unitId: string, options?: FullScreenAdOptions) {
22 | const requestId = _interstitialRequest++;
23 | return new InterstitialAd(requestId, unitId, options);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/ads/fullscreen/RewardedAd.ts:
--------------------------------------------------------------------------------
1 | import {
2 | FullScreenAdOptions,
3 | RewardedAdEvent,
4 | RewardedAdHandlerType,
5 | } from '../../types';
6 |
7 | import FullScreenAd from './FullScreenAd';
8 |
9 | let _rewardedRequest = 0;
10 |
11 | export default class RewardedAd extends FullScreenAd<
12 | RewardedAdEvent,
13 | RewardedAdHandlerType
14 | > {
15 | private constructor(
16 | requestId: number,
17 | unitId: string,
18 | options?: FullScreenAdOptions
19 | ) {
20 | super('Rewarded', requestId, unitId, options);
21 | }
22 |
23 | /**
24 | * Creates a new RewardedAd instance.
25 | * @param unitId The Ad Unit ID for the Rewarded Ad. You can find this on your Google AdMob dashboard.
26 | * @param options Optional FullScreenAdOptions for this ad.
27 | */
28 | static createAd(unitId: string, options?: FullScreenAdOptions) {
29 | const requestId = _rewardedRequest++;
30 | return new RewardedAd(requestId, unitId, options);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/ads/fullscreen/RewardedInterstitialAd.ts:
--------------------------------------------------------------------------------
1 | import {
2 | FullScreenAdOptions,
3 | RewardedAdEvent,
4 | RewardedAdHandlerType,
5 | } from '../../types';
6 |
7 | import FullScreenAd from './FullScreenAd';
8 |
9 | let _rewardedInterstitialRequest = 0;
10 |
11 | export default class RewardedInterstitialAd extends FullScreenAd<
12 | RewardedAdEvent,
13 | RewardedAdHandlerType
14 | > {
15 | private constructor(
16 | requestId: number,
17 | unitId: string,
18 | options?: FullScreenAdOptions
19 | ) {
20 | super('RewardedInterstitial', requestId, unitId, options);
21 | }
22 |
23 | /**
24 | * Creates a new RewardedInterstitialAd instance.
25 | * @param unitId The Ad Unit ID for the Rewarded Interstitial Ad. You can find this on your Google AdMob dashboard.
26 | * @param options Optional FullScreenAdOptions for this ad.
27 | */
28 | static createAd(unitId: string, options?: FullScreenAdOptions) {
29 | const requestId = _rewardedInterstitialRequest++;
30 | return new RewardedInterstitialAd(requestId, unitId, options);
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/ads/fullscreen/index.ts:
--------------------------------------------------------------------------------
1 | export { default as InterstitialAd } from './InterstitialAd';
2 | export { default as RewardedAd } from './RewardedAd';
3 | export { default as RewardedInterstitialAd } from './RewardedInterstitialAd';
4 | export { default as AppOpenAd } from './AppOpenAd';
5 |
--------------------------------------------------------------------------------
/src/ads/index.ts:
--------------------------------------------------------------------------------
1 | export * from './banner';
2 | export * from './fullscreen';
3 | export { default as AppOpenAdProvider } from './AppOpenAdProvider';
4 |
--------------------------------------------------------------------------------
/src/constants/BannerAdSize.ts:
--------------------------------------------------------------------------------
1 | export default {
2 | BANNER: 'BANNER',
3 | LARGE_BANNER: 'LARGE_BANNER',
4 | MEDIUM_RECTANGLE: 'MEDIUM_RECTANGLE',
5 | FULL_BANNER: 'FULL_BANNER',
6 | LEADERBOARD: 'LEADERBOARD',
7 | ADAPTIVE_BANNER: 'ADAPTIVE_BANNER',
8 | };
9 |
--------------------------------------------------------------------------------
/src/constants/TestIds.ts:
--------------------------------------------------------------------------------
1 | import { Platform } from 'react-native';
2 |
3 | export default {
4 | ...Platform.select({
5 | default: {
6 | APP_OPEN: 'ca-app-pub-3940256099942544/3419835294',
7 | BANNER: 'ca-app-pub-3940256099942544/6300978111',
8 | INTERSTITIAL: 'ca-app-pub-3940256099942544/1033173712',
9 | INTERSTITIAL_VIDEO: 'ca-app-pub-3940256099942544/8691691433',
10 | REWARDED: 'ca-app-pub-3940256099942544/5224354917',
11 | REWARDED_INTERSTITIAL: 'ca-app-pub-3940256099942544/5354046379',
12 | NATIVE_ADVANCED: 'ca-app-pub-3940256099942544/2247696110',
13 | NATIVE_ADVANCED_VIDEO: 'ca-app-pub-3940256099942544/1044960115',
14 | },
15 | ios: {
16 | APP_OPEN: 'ca-app-pub-3940256099942544/5662855259',
17 | BANNER: 'ca-app-pub-3940256099942544/2934735716',
18 | INTERSTITIAL: 'ca-app-pub-3940256099942544/4411468910',
19 | INTERSTITIAL_VIDEO: 'ca-app-pub-3940256099942544/5135589807',
20 | REWARDED: 'ca-app-pub-3940256099942544/1712485313',
21 | REWARDED_INTERSTITIAL: 'ca-app-pub-3940256099942544/6978759866',
22 | NATIVE_ADVANCED: 'ca-app-pub-3940256099942544/3986624511',
23 | NATIVE_ADVANCED_VIDEO: 'ca-app-pub-3940256099942544/2521693316',
24 | },
25 | }),
26 | };
27 |
--------------------------------------------------------------------------------
/src/constants/index.ts:
--------------------------------------------------------------------------------
1 | export { default as BannerAdSize } from './BannerAdSize';
2 | export { default as TestIds } from './TestIds';
3 |
--------------------------------------------------------------------------------
/src/hooks/index.ts:
--------------------------------------------------------------------------------
1 | export { default as useInterstitialAd } from './useInterstitialAd';
2 | export { default as useRewardedAd } from './useRewardedAd';
3 | export { default as useRewardedInterstitialAd } from './useRewardedInterstitialAd';
4 | export { default as useAppOpenAd } from './useAppOpenAd';
5 |
--------------------------------------------------------------------------------
/src/hooks/useAppOpenAd.ts:
--------------------------------------------------------------------------------
1 | import { useContext } from 'react';
2 |
3 | import AppOpenAdContext from '../ads/AppOpenAdContext';
4 | import { AdHookReturns } from '../types';
5 |
6 | import useFullScreenAd from './useFullScreenAd';
7 |
8 | /**
9 | * React Hook for AdMob App Open Ad.
10 | * Must be created inside `AppOpenAdProvider`.
11 | */
12 | export default function useAppOpenAd(): Omit {
13 | const appOpenAdContext = useContext(AppOpenAdContext);
14 | if (!appOpenAdContext) {
15 | throw new Error(
16 | 'AppOpenAdProvider is not found. You should wrap your components with AppOpenProvider to use useAppOpenAd hook.'
17 | );
18 | }
19 |
20 | return useFullScreenAd(appOpenAdContext.appOpenAd);
21 | }
22 |
--------------------------------------------------------------------------------
/src/hooks/useFullScreenAd.ts:
--------------------------------------------------------------------------------
1 | import { Reducer, useCallback, useEffect, useReducer } from 'react';
2 |
3 | import AdError from '../AdError';
4 | import {
5 | AppOpenAd,
6 | InterstitialAd,
7 | RewardedAd,
8 | RewardedInterstitialAd,
9 | } from '../ads/fullscreen';
10 | import {
11 | AdHookReturns,
12 | FullScreenAdState,
13 | RequestOptions,
14 | Reward,
15 | } from '../types';
16 |
17 | const initialState: FullScreenAdState = {
18 | adLoaded: false,
19 | adPresented: false,
20 | adDismissed: false,
21 | adLoadError: undefined,
22 | adPresentError: undefined,
23 | reward: undefined,
24 | };
25 |
26 | export default function useFullScreenAd<
27 | T extends
28 | | InterstitialAd
29 | | RewardedAd
30 | | RewardedInterstitialAd
31 | | AppOpenAd
32 | | null
33 | >(ad: T): AdHookReturns {
34 | const [state, setState] = useReducer<
35 | Reducer>
36 | >((prevState, newState) => ({ ...prevState, ...newState }), initialState);
37 | const adShowing = state.adPresented && !state.adDismissed;
38 |
39 | const load = useCallback(
40 | (requestOptions?: RequestOptions) => {
41 | if (ad) {
42 | setState(initialState);
43 | ad.load(requestOptions).catch(() => {});
44 | }
45 | },
46 | [ad]
47 | );
48 |
49 | const show = useCallback(() => {
50 | if (ad) {
51 | ad.show().catch(() => {});
52 | }
53 | }, [ad]);
54 |
55 | useEffect(() => {
56 | setState(initialState);
57 | if (!ad) {
58 | return;
59 | }
60 | const listeners = [
61 | ad.addEventListener('adLoaded', () => setState({ adLoaded: true })),
62 | ad.addEventListener('adFailedToLoad', (error: AdError) =>
63 | setState({ adLoadError: error })
64 | ),
65 | ad.addEventListener('adPresented', () => setState({ adPresented: true })),
66 | ad.addEventListener('adFailedToPresent', (error: AdError) =>
67 | setState({ adPresentError: error })
68 | ),
69 | ad.addEventListener('adDismissed', () => {
70 | setState({ adDismissed: true });
71 | if (ad.options.loadOnDismissed) {
72 | setState(initialState);
73 | }
74 | }),
75 | ad.type === 'Rewarded' || ad.type === 'RewardedInterstitial'
76 | ? (ad as RewardedAd | RewardedInterstitialAd).addEventListener(
77 | 'rewarded',
78 | (reward: Reward) => setState({ reward })
79 | )
80 | : undefined,
81 | ];
82 | return () => {
83 | listeners.forEach((listener) => listener?.remove());
84 | };
85 | }, [ad]);
86 |
87 | return {
88 | ...state,
89 | adShowing,
90 | load,
91 | show,
92 | };
93 | }
94 |
--------------------------------------------------------------------------------
/src/hooks/useInterstitialAd.ts:
--------------------------------------------------------------------------------
1 | import { useState } from 'react';
2 | import useDeepCompareEffect from 'use-deep-compare-effect';
3 |
4 | import { InterstitialAd } from '../ads/fullscreen';
5 | import { AdHookReturns, FullScreenAdOptions } from '../types';
6 |
7 | import useFullScreenAd from './useFullScreenAd';
8 |
9 | /**
10 | * React Hook for AdMob Interstitial Ad.
11 | * @param unitId Interstitial Ad Unit Id
12 | * @param options `FullScreenAdOptions`
13 | */
14 | export default function useInterstitialAd(
15 | unitId: string | null,
16 | options: FullScreenAdOptions = {}
17 | ): Omit {
18 | const [interstitialAd, setInterstitialAd] = useState(
19 | null
20 | );
21 |
22 | useDeepCompareEffect(() => {
23 | setInterstitialAd((prevAd) => {
24 | prevAd?.destroy();
25 | return unitId ? InterstitialAd.createAd(unitId, options) : null;
26 | });
27 | }, [unitId, options]);
28 |
29 | return useFullScreenAd(interstitialAd);
30 | }
31 |
--------------------------------------------------------------------------------
/src/hooks/useRewardedAd.ts:
--------------------------------------------------------------------------------
1 | import { useState } from 'react';
2 | import useDeepCompareEffect from 'use-deep-compare-effect';
3 |
4 | import { RewardedAd } from '../ads/fullscreen';
5 | import { AdHookReturns, FullScreenAdOptions } from '../types';
6 |
7 | import useFullScreenAd from './useFullScreenAd';
8 |
9 | /**
10 | * React Hook for AdMob Rewarded Ad.
11 | * @param unitId Rewarded Ad Unit Id
12 | * @param options `FullScreenAdOptions`
13 | */
14 | export default function useRewardedAd(
15 | unitId: string | null,
16 | options: FullScreenAdOptions = {}
17 | ): AdHookReturns {
18 | const [rewardedAd, setRewardedAd] = useState(null);
19 |
20 | useDeepCompareEffect(() => {
21 | setRewardedAd((prevAd) => {
22 | prevAd?.destroy();
23 | return unitId ? RewardedAd.createAd(unitId, options) : null;
24 | });
25 | }, [unitId, options]);
26 |
27 | return useFullScreenAd(rewardedAd);
28 | }
29 |
--------------------------------------------------------------------------------
/src/hooks/useRewardedInterstitialAd.ts:
--------------------------------------------------------------------------------
1 | import { useState } from 'react';
2 | import useDeepCompareEffect from 'use-deep-compare-effect';
3 |
4 | import { RewardedInterstitialAd } from '../ads/fullscreen';
5 | import { AdHookReturns, FullScreenAdOptions } from '../types';
6 |
7 | import useFullScreenAd from './useFullScreenAd';
8 |
9 | /**
10 | * React Hook for AdMob Rewarded Interstitial Ad.
11 | * @param unitId Rewarded Interstitial Ad Unit Id
12 | * @param options `FullScreenAdOptions`
13 | */
14 | export default function useRewardedInterstitialAd(
15 | unitId: string | null,
16 | options: FullScreenAdOptions = {}
17 | ): AdHookReturns {
18 | const [rewardedInterstitialAd, setRewardedInterstitialAd] =
19 | useState(null);
20 |
21 | useDeepCompareEffect(() => {
22 | setRewardedInterstitialAd((prevAd) => {
23 | prevAd?.destroy();
24 | return unitId ? RewardedInterstitialAd.createAd(unitId, options) : null;
25 | });
26 | }, [unitId, options]);
27 |
28 | return useFullScreenAd(rewardedInterstitialAd);
29 | }
30 |
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
1 | import AdMob from './AdMob';
2 | export default AdMob;
3 |
4 | export * from './ads';
5 | export * from './constants';
6 | export * from './hooks';
7 |
8 | export * from './types';
9 | export { default as AdError } from './AdError';
10 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "baseUrl": ".",
4 | "paths": {
5 | "@react-native-admob/admob": [
6 | "./src"
7 | ]
8 | },
9 | "esModuleInterop": true,
10 | "forceConsistentCasingInFileNames": true,
11 | "jsx": "react-native",
12 | "lib": [
13 | "esnext"
14 | ],
15 | "target": "esnext",
16 | "module": "esnext",
17 | "moduleResolution": "node",
18 | "skipLibCheck": true,
19 | "strict": true
20 | },
21 | "include": [
22 | "src/**/*.ts",
23 | "src/**/*.tsx"
24 | ]
25 | }
26 |
--------------------------------------------------------------------------------