如何离线隐藏广告横幅或无法加载广告 - 在 React Native with Expo 中?

How to hide ad banner offline or when no ad could be loaded - in React Native with Expo?

我在我的 React 本机应用程序中使用 expo 和 admob 实现了广告,但我想在没有加载广告时摆脱 blank/blocking space。还没有找到任何例子。 (除了横幅,我在那个页面上有一个 header 和滚动视图)。 admob 横幅是这样实现的:

// Display a banner
<AdMobBanner
  bannerSize="fullBanner"
  adUnitID="ca-app-pub-3940256099942544/6300978111" // Test ID, Replace    with your-admob-unit-id
  testDeviceID="EMULATOR" />

通过阅读他们的文档,您可以使用 2 种方法:

onAdLoaded

Accepts a function. Called when an ad is received.

onAdFailedToLoad

Accepts a function. Called when an ad request failed.

如果您处于离线状态,您可以像这样检查网络状态:

文档:https://facebook.github.io/react-native/docs/netinfo

NetInfo.getConnectionInfo().then((connectionInfo) => {
  console.log('Initial, type: ' + connectionInfo.type + ', effectiveType: ' + connectionInfo.effectiveType);
});
function handleFirstConnectivityChange(connectionInfo) {
  console.log('First change, type: ' + connectionInfo.type + ', effectiveType: ' + connectionInfo.effectiveType);
  NetInfo.removeEventListener(
    'connectionChange',
    handleFirstConnectivityChange
  );
}
NetInfo.addEventListener(
  'connectionChange',
  handleFirstConnectivityChange
);

我会检查用户是否离线或网络连接不佳 - 如果在线 - 呈现广告,并使用 onAdFailedToLoad 方法处理广告错误。

我尝试了几种方法... onAdFailedToLoad 的问题是它在离线时似乎不起作用。监听 NetInfo 的问题是,一个简单的实现仅在更改后告知网络状态。

我最终使用库来发现该应用程序是否在线:

https://github.com/rgommezz/react-native-offline(使用 redux 实现)

以及这种隐藏我的 admob 横幅的方法(嵌套在 MyView 中):

https://medium.com/scripbox-engineering/how-to-hide-a-view-component-in-react-native-8a4994382c0.

我对这个问题的解决方案是将 admob 组件包装在具有样式的视图中,以将高度设置为零。当您收到广告时。然后更新样式以在视图中显示横幅

export class AdContainer extends React.Component {
  constructor() {
    super();
    this.state = { height: 0 };
  }

  bannerError(e) {
    console.log('banner error: ');
    console.log(e);
  }
  adReceived() {
    console.log('banner ad received: ');
    this.setState({
      ...this.state,
      hasAd: true
    });
  }
  adClicked() {
    console.log('banner ad clicked: ');
  }

  render() {
    return (
      <View style={!this.state.hasAd ? { height: 0 } : {}}>
        <View>
          <AdMobBanner
            bannerSize="smartBannerPortrait" // "largeBanner" "fullBanner"
            adUnitID={BANNER_ID}
            testDeviceID="EMULATOR"
            onDidFailToReceiveAdWithError={this.bannerError}
            onAdViewDidReceiveAd={this.adReceived.bind(this)}
            onAdViewWillPresentScreen={this.adClicked.bind(this)}
          />
        </View>
      </View>
    );
  }
}