Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Admob — Ad failed to show: The provided view controller is not being presented. #38

Open
nprk opened this issue Jul 9, 2024 · 1 comment
Labels
transmitted Issue transmitted to inner service

Comments

@nprk
Copy link

nprk commented Jul 9, 2024

Description:
The issue occurs every time when attempting to show rewarded ads or interstitial ads from AdMob (demo-rewarded-admob or a real adUnitId); admob ad loading is successful. Other ad networks load and show correctly.

Device:
iOS

Result:

onAdLoaded
onAdFailedToShow - Ad failed to show: The provided view controller is not being presented.

Related issues:
googleads/googleads-mobile-flutter#700
googleads/googleads-mobile-flutter#845

Pubspec:
yandex_mobileads: ^7.1.0

Podfile:

source 'https://cdn.cocoapods.org'

platform :ios, '13.0'

install! 'cocoapods', warn_for_unused_master_specs_repo: false

use_frameworks!

# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def yandexAds
  pod 'YandexMobileAdsMediation', '7.1.1'
end

def flutter_root
  generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
  unless File.exist?(generated_xcode_build_settings_path)
    raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
  end

  File.foreach(generated_xcode_build_settings_path) do |line|
    matches = line.match(/FLUTTER_ROOT\=(.*)/)
    return matches[1].strip if matches
  end
  raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end

require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)

flutter_ios_podfile_setup

target 'Runner' do
  use_frameworks!
  use_modular_headers!
  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))

  yandexAds
end

# Fix:
# [!] The 'Pods-Runner' target has transitive dependencies
# that include statically linked binaries: (.. /ios/Pods/YandexMobileAds/static/YandexMobileAds.xcframework)
# https://github.com/yandexmobile/yandex-ads-flutter-plugin/issues/30
static_frameworks = ['YandexMobileAds', 'yandex_mobileads']
pre_install do |installer|
  installer.pod_targets.each do |pod|
    if static_frameworks.include?(pod.name)
      def pod.static_framework?;
        true
      end
      def pod.build_type;
        Pod::BuildType.static_library
      end
    end
  end
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)
  end
end

Example:

import 'package:flutter/material.dart';
import 'package:yandex_mobileads/mobile_ads.dart';

class AdScreen extends StatefulWidget {
  const AdScreen({super.key});

  @override
  State<AdScreen> createState() => _AdScreenState();
}

class _AdScreenState extends State<AdScreen> {
  late final Future<RewardedAdLoader> _adLoader;

  final adId = "demo-rewarded-admob";

  RewardedAd? _ad;

  @override
  void initState() {
    super.initState();
    MobileAds.initialize();
    _adLoader = _createRewardedAdLoader();
    _loadRewardedAd();
  }

  Future<RewardedAdLoader> _createRewardedAdLoader() {
    return RewardedAdLoader.create(
      onAdLoaded: (RewardedAd rewardedAd) {
        print("onAdLoaded");
        // The ad was loaded successfully. Now you can show loaded ad
        _ad = rewardedAd;
      },
      onAdFailedToLoad: (error) {
        print("onAdFailedToLoad");
        // Ad failed to load with AdRequestError.
        // Attempting to load a new ad from the onAdFailedToLoad() method is strongly discouraged.
      },
    );
  }

  Future<void> _loadRewardedAd() async {
    final adLoader = await _adLoader;
    await adLoader.loadAd(adRequestConfiguration: AdRequestConfiguration(adUnitId: adId));
  }

  _showAd() async {
    _ad?.setAdEventListener(
        eventListener: RewardedAdEventListener(
            onAdShown: () {
              print("onAdShown");
              // Called when ad is shown.
            },
            onAdFailedToShow: (error) {
              print("onAdFailedToShow - $error");
              // Called when an ad failed to show.
              // Destroy the ad so you don't show the ad a second time.
              _ad?.destroy();
              _ad = null;

              // Now you can preload the next ad.
              _loadRewardedAd();
            },
            onAdClicked: () {
              print("onAdClicked");
              // Called when a click is recorded for an ad.
            },
            onAdDismissed: () {
              print("onAdDismissed");
              // Called when ad is dismissed.
              // Destroy the ad so you don't show the ad a second time.
              _ad?.destroy();
              _ad = null;

              // Now you can preload the next ad.
              _loadRewardedAd();
            },
            onAdImpression: (impressionData) {
              print("onAdImpression");
              // Called when an impression is recorded for an ad.
            },
            onRewarded: (Reward reward) {
              print("onRewarded");
              // Called when the user can be rewarded.
            }
        ));

    await _ad?.show();
    final reward = await _ad?.waitForDismiss();
    if (reward != null) {
      print('got ${reward.amount} of ${reward.type}');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Ad'),
      ),
      body: Container(
        margin: const EdgeInsets.all(16),
        child: Column(
          children: [
            Row(
              children: [
                TextButton(
                    child: Text("load"),
                    onPressed: () {
                      _ad?.destroy();
                      _ad = null;
                      _loadRewardedAd();
                    }
                ),
                TextButton(
                    child: Text("show"),
                    onPressed: () {
                      _showAd();
                    }
                ),
              ],
            ),
          ],
        ),
      )
    );
  }
}
@mobile-ads-github
Copy link
Collaborator

Спасибо за Ваше обращение, для разбора создана задача с номером PCODESUP-3427. Мы ознакомимся и вернемся с ответом в течение 2 дней, возможно запросим дополнительную информацию.

Thank you for your message, a task with the number PCODESUP-3427 has been created for analysis. We will get acquainted and return with the answer within 2 days, we may request additional information.

@mobile-ads-github mobile-ads-github added the transmitted Issue transmitted to inner service label Jul 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
transmitted Issue transmitted to inner service
Projects
None yet
Development

No branches or pull requests

2 participants