React Native Google Ad Manager 使用教程

时间:2020-9-9 作者:admin

安装npm包

我们通过 react-native-ad-manager这个包实现在rn中使用 Google Ad Manager

npm i react-native-ad-manager

配置原生文件

Android

AndroidManifest.xml

<manifest>
    <application>
        <meta-data
            android:name="com.google.android.gms.ads.AD_MANAGER_APP"
            android:value="true"/>
    </application>
</manifest>

IOS

由于没有配置过IOS,请自行参考以下文档说明。

Alternatively for iOS you can install the library with CocoaPods by adding a line to your Podfile;

pod 'react-native-ad-manager', path: '../node_modules/react-native-ad-manager'

For iOS you will have to add the Google Mobile Ads SDK to your Xcode project.

使用

在完成前置配置只有就可以直接coding啦~

index.js

import {
  Banner,
  Interstitial,
  PublisherBanner,
  NativeAdsManager,
} from 'react-native-ad-manager'
 
// Display a DFP Publisher banner
<Banner
  adSize="fullBanner"
  adUnitID="your-ad-unit-id"
  testDevices={[PublisherBanner.simulatorId]}
  onAdFailedToLoad={error => console.error(error)}
  onAppEvent={event => console.log(event.name, event.info)}
/>
 
// Display an interstitial
Interstitial.setAdUnitID('your-ad-unit-id');
Interstitial.setTestDevices([Interstitial.simulatorId]);
Interstitial.requestAd().then(() => Interstitial.showAd());
 
// Native ad
import NativeAdView from './NativeAdView';
const adsManager = new NativeAdsManager('your-ad-unit-id', []);
<NativeAdView
    targeting={{
        customTargeting: {group: 'user_test'},
        categoryExclusions: ['media'],
        contentURL: 'test://',
        publisherProvidedID: 'provider_id',
    }}
    style={{width: '100%'}}
    adsManager={adsManager}
    validAdTypes={['native', 'template']}
    customTemplateIds={['your-template-id-1', 'your-template-id-2']}
    onAdLoaded={ad => {
        console.log(ad);
    }}
    onAdFailedToLoad={error => {
        console.log(error);
    }}
/>

NativeAdView.js

import React, { Component } from 'react';
import { Text, View, Image } from 'react-native';
import {
  withNativeAd,
  TriggerableView,
} from 'react-native-ad-manager';

export class NativeAdView extends Component {
  render() {
    const { nativeAd } = this.props;
    if (!['native', 'template'].includes(nativeAd?.type)) {
      return null;
    }

    let data = {};
    if (nativeAd?.type == 'native') {
      data.headline = nativeAd?.headline;
      data.bodyText = nativeAd?.bodyText;
      data.advertiserName = nativeAd?.advertiserName;
      data.starRating = nativeAd?.starRating;
      data.storeName = nativeAd?.storeName;
      data.price = nativeAd?.price;
      data.icon = nativeAd?.icon;
      data.callToActionText = nativeAd?.callToActionText;
      data.images = nativeAd?.images;
    } else if (nativeAd?.type == 'template') {
      data.headline = nativeAd?.title;
      data.bodyText = nativeAd?.text;
      data.advertiserName = nativeAd?.label;
      data.starRating = nativeAd?.imptrk;
      data.storeName = nativeAd?.headline;
      data.price = null;
      data.icon = nativeAd?.image;
      data.callToActionText = null;
      data.images = [];
    }

    return (
      <View style={{ flexDirection: 'column', borderWidth: 1, position: 'relative' }}>
        <TriggerableView style={{backgroundColor: 'rgba(52, 52, 52, 0.5)', position: 'absolute', zIndex:99, top:0, left:0, width: '100%', height: '100%'}} />
        <View style={{ flexDirection: 'row', padding: 10 }}>
          <View
            style={{ flexDirection: 'column', flex: 1 }}
          >
            {data?.headline && (<Text style={{ fontSize: 18 }}>
              {data.headline}
            </Text>)}
            {data?.bodyText && (<Text style={{ fontSize: 10 }}>
              {data.bodyText}
            </Text>)}
            <View style={{ flexDirection: 'row' }}>
              <Text>{data?.advertiserName}</Text>
              <Text>{data?.starRating}</Text>
              <Text>{data?.storeName}</Text>
              <Text>{data?.price}</Text>
            </View>
          </View>
          {data?.icon?.uri && (<Image style={{ width: 80, height: 80 }} source={{uri: data.icon.uri}} />)}
        </View>
        {data?.callToActionText && (<View style={{ alignItems: 'center' }}>
          <View
            ref={el => (this._triggerView = el)}>
            <Text
              style={{
                fontSize: 15,
                color: '#a70f0a',
                paddingVertical: 10,
                paddingHorizontal: 30,
                elevation: 3,
                borderTopWidth: 0,
                margin: 10,
                borderRadius: 6,
              }}
            >
              {data.callToActionText}
            </Text>
          </View>
        </View>)}
      </View>
    );
  }
}

export default withNativeAd(NativeAdView);

终于coding完了,然鹅我们会发现此时并没有看到所谓的广告,这是因为在代码我们还需要将具体的 ad unit id填充入相应位置。在官方文档中提供了几个 test ad unit id,但是不知道是不是我的网络问题,还是他的示例中资源不足,所以有些广告并刷不出来或者需要多刷新几次才能看到。

示例广告单元

广告格式 示例广告单元ID
横幅广告 /6499/example/banner
插页式广告 /6499/example/interstitial
激励视频广告 /6499/example/rewarded-video
自定义呈现广告 /6499/example/native
自定义呈现视频广告 /6499/example/native-video

将代码中 your-ad-unit-id替换成想要的 示例广告单元ID即可。

这时候我们应该已经能够看到一些测试广告了,但这肯定还不满足我们的需求,所以接下来我们需要去配置 Google Ad Manager。

Google Ad Manager 配置教程

声明:本文内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎进行举报,并提供相关证据,工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。