تنظیمات بومی در اندروید و iOS

تبلیغات بومی با استفاده از اجزای رابط کاربری بومی پلتفرم به کاربران ارائه می‌شوند - برای مثال، یک View در اندروید یا یک UIView در iOS.

این راهنما به شما نشان می‌دهد که چگونه تبلیغات بومی را با استفاده از کد مخصوص پلتفرم بارگذاری، نمایش و سفارشی‌سازی کنید.

پیش‌نیازها

همیشه با تبلیغات آزمایشی تست کنید

هنگام ساخت و آزمایش برنامه‌های خود، مطمئن شوید که از تبلیغات آزمایشی به جای تبلیغات زنده و تولیدی استفاده می‌کنید. ساده‌ترین راه برای بارگذاری تبلیغات آزمایشی، استفاده از شناسه واحد تبلیغات آزمایشی اختصاصی ما برای تبلیغات بومی است:

اندروید

ca-app-pub-3940256099942544/2247696110

آی‌او‌اس

ca-app-pub-3940256099942544/3986624511

واحدهای تبلیغاتی آزمایشی طوری پیکربندی شده‌اند که برای هر درخواست، تبلیغات آزمایشی را برگردانند، بنابراین می‌توانید از آنها در برنامه‌های خود هنگام کدنویسی، آزمایش و اشکال‌زدایی استفاده کنید - فقط قبل از انتشار برنامه خود، مطمئن شوید که آنها را با شناسه‌های واحدهای تبلیغاتی خود جایگزین می‌کنید.

تنظیمات خاص پلتفرم

برای ایجاد تبلیغات بومی خود، باید کد مخصوص پلتفرم را برای iOS و اندروید بنویسید و سپس پیاده‌سازی Dart خود را اصلاح کنید تا از تغییرات کد بومی که ایجاد کرده‌اید، بهره‌مند شوید.

اندروید

افزونه را وارد کنید

پیاده‌سازی اندروید افزونه تبلیغات موبایلی گوگل (Google Mobile Ads) نیاز به یک کلاس دارد که API NativeAdFactory پیاده‌سازی کند. برای ارجاع به این API از پروژه اندروید خود، خطوط زیر را به settings.gradle خود اضافه کنید:

def flutterProjectRoot = rootProject.projectDir.parentFile.toPath()
def plugins = new Properties()
def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins')
if (pluginsFile.exists()) {
    pluginsFile.withInputStream { stream -> plugins.load(stream) }
}

plugins.each { name, path ->
    def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile()
    include ":$name"
    project(":$name").projectDir = pluginDirectory
}

پیاده‌سازی NativeAdFactory

در مرحله بعد، یک کلاس ایجاد کنید که NativeAdFactory را پیاده‌سازی کند و متد createNativeAd() را بازنویسی کند.

package io.flutter.plugins.googlemobileadsexample;

import android.graphics.Color;
import android.view.LayoutInflater;
import android.widget.TextView;
import com.google.android.gms.ads.nativead.NativeAd;
import com.google.android.gms.ads.nativead.NativeAdView;
import io.flutter.plugins.googlemobileads.GoogleMobileAdsPlugin.NativeAdFactory;
import java.util.Map;

/**
 * my_native_ad.xml can be found at
 * github.com/googleads/googleads-mobile-flutter/blob/main/packages/google_mobile_ads/
 *     example/android/app/src/main/res/layout/my_native_ad.xml
 */
class NativeAdFactoryExample implements NativeAdFactory {
  private final LayoutInflater layoutInflater;

  NativeAdFactoryExample(LayoutInflater layoutInflater) {
    this.layoutInflater = layoutInflater;
  }

  @Override
  public NativeAdView createNativeAd(
      NativeAd nativeAd, Map<String, Object> customOptions) {
    final NativeAdView adView =
        (NativeAdView) layoutInflater.inflate(R.layout.my_native_ad, null);

    // Set the media view.
    adView.setMediaView((MediaView) adView.findViewById(R.id.ad_media));

    // Set other ad assets.
    adView.setHeadlineView(adView.findViewById(R.id.ad_headline));
    adView.setBodyView(adView.findViewById(R.id.ad_body));
    adView.setCallToActionView(adView.findViewById(R.id.ad_call_to_action));
    adView.setIconView(adView.findViewById(R.id.ad_app_icon));
    adView.setPriceView(adView.findViewById(R.id.ad_price));
    adView.setStarRatingView(adView.findViewById(R.id.ad_stars));
    adView.setStoreView(adView.findViewById(R.id.ad_store));
    adView.setAdvertiserView(adView.findViewById(R.id.ad_advertiser));

    // The headline and mediaContent are guaranteed to be in every NativeAd.
    ((TextView) adView.getHeadlineView()).setText(nativeAd.getHeadline());
    adView.getMediaView().setMediaContent(nativeAd.getMediaContent());

    // These assets aren't guaranteed to be in every NativeAd, so it's important to
    // check before trying to display them.
    if (nativeAd.getBody() == null) {
      adView.getBodyView().setVisibility(View.INVISIBLE);
    } else {
      adView.getBodyView().setVisibility(View.VISIBLE);
      ((TextView) adView.getBodyView()).setText(nativeAd.getBody());
    }

    if (nativeAd.getCallToAction() == null) {
      adView.getCallToActionView().setVisibility(View.INVISIBLE);
    } else {
      adView.getCallToActionView().setVisibility(View.VISIBLE);
      ((Button) adView.getCallToActionView()).setText(nativeAd.getCallToAction());
    }

    if (nativeAd.getIcon() == null) {
      adView.getIconView().setVisibility(View.GONE);
    } else {
      ((ImageView) adView.getIconView()).setImageDrawable(nativeAd.getIcon().getDrawable());
      adView.getIconView().setVisibility(View.VISIBLE);
    }

    if (nativeAd.getPrice() == null) {
      adView.getPriceView().setVisibility(View.INVISIBLE);
    } else {
      adView.getPriceView().setVisibility(View.VISIBLE);
      ((TextView) adView.getPriceView()).setText(nativeAd.getPrice());
    }

    if (nativeAd.getStore() == null) {
      adView.getStoreView().setVisibility(View.INVISIBLE);
    } else {
      adView.getStoreView().setVisibility(View.VISIBLE);
      ((TextView) adView.getStoreView()).setText(nativeAd.getStore());
    }

    if (nativeAd.getStarRating() == null) {
      adView.getStarRatingView().setVisibility(View.INVISIBLE);
    } else {
      ((RatingBar) adView.getStarRatingView()).setRating(nativeAd.getStarRating()
          .floatValue());
      adView.getStarRatingView().setVisibility(View.VISIBLE);
    }

    if (nativeAd.getAdvertiser() == null) {
      adView.getAdvertiserView().setVisibility(View.INVISIBLE);
    } else {
      adView.getAdvertiserView().setVisibility(View.VISIBLE);
      ((TextView) adView.getAdvertiserView()).setText(nativeAd.getAdvertiser());
    }

    // This method tells Google Mobile Ads SDK that you have finished populating your
    // native ad view with this native ad.
    adView.setNativeAd(nativeAd);

    return adView;
  }
}

برای مثالی از پیکربندی طرح‌بندی NativeAdView خود، به my_native_ad.xml مراجعه کنید.

NativeAdFactory خود را ثبت کنید

هر پیاده‌سازی NativeAdFactory هنگام فراخوانی MainActivity.configureFlutterEngine(FlutterEngine) باید با یک factoryId ، یک شناسه String منحصر به فرد، ثبت شود. factoryId بعداً هنگام نمونه‌سازی یک تبلیغ بومی از کد Dart استفاده خواهد شد.

یک NativeAdFactory می‌تواند برای هر طرح‌بندی تبلیغات بومی منحصر به فرد مورد استفاده در برنامه شما پیاده‌سازی و ثبت شود، یا یک طرح‌بندی واحد می‌تواند تمام طرح‌بندی‌ها را مدیریت کند.

توجه داشته باشید که هنگام ساخت با add-to-app ، NativeAdFactory نیز باید در cleanUpFlutterEngine(engine) ثبت نشده باشد.

پس از ایجاد NativeAdFactoryExample ، MainActivity خود را به صورت زیر تنظیم کنید:

package my.app.path;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugins.googlemobileads.GoogleMobileAdsPlugin;

public class MainActivity extends FlutterActivity {
  @Override
  public void configureFlutterEngine(FlutterEngine flutterEngine) {
    flutterEngine.getPlugins().add(new GoogleMobileAdsPlugin());
    super.configureFlutterEngine(flutterEngine);

    GoogleMobileAdsPlugin.registerNativeAdFactory(flutterEngine,
        "adFactoryExample", NativeAdFactoryExample());
  }

  @Override
  public void cleanUpFlutterEngine(FlutterEngine flutterEngine) {
    GoogleMobileAdsPlugin.unregisterNativeAdFactory(flutterEngine, "adFactoryExample");
  }
}

آی‌او‌اس

پیاده‌سازی NativeAdFactory

پیاده‌سازی iOS افزونه تبلیغات موبایلی گوگل نیازمند کلاسی است که API FLTNativeAdFactory را پیاده‌سازی کند. کلاسی ایجاد کنید که NativeAdFactory را پیاده‌سازی کند و متد createNativeAd() را پیاده‌سازی کند.

#import "FLTGoogleMobileAdsPlugin.h"

/**
 * The example NativeAdView.xib can be found at
 * github.com/googleads/googleads-mobile-flutter/blob/main/packages/google_mobile_ads/
 *     example/ios/Runner/NativeAdView.xib
 */
@interface NativeAdFactoryExample : NSObject <FLTNativeAdFactory>
@end

@implementation NativeAdFactoryExample
- (GADNativeAdView *)createNativeAd:(GADNativeAd *)nativeAd
                      customOptions:(NSDictionary *)customOptions {
  // Create and place the ad in the view hierarchy.
  GADNativeAdView *adView =
      [[NSBundle mainBundle] loadNibNamed:@"NativeAdView" owner:nil options:nil].firstObject;

  // Populate the native ad view with the native ad assets.
  // The headline is guaranteed to be present in every native ad.
  ((UILabel *)adView.headlineView).text = nativeAd.headline;

  // These assets are not guaranteed to be present. Check that they are before
  // showing or hiding them.
  ((UILabel *)adView.bodyView).text = nativeAd.body;
  adView.bodyView.hidden = nativeAd.body ? NO : YES;

  [((UIButton *)adView.callToActionView) setTitle:nativeAd.callToAction
                                         forState:UIControlStateNormal];
  adView.callToActionView.hidden = nativeAd.callToAction ? NO : YES;

  ((UIImageView *)adView.iconView).image = nativeAd.icon.image;
  adView.iconView.hidden = nativeAd.icon ? NO : YES;

  ((UILabel *)adView.storeView).text = nativeAd.store;
  adView.storeView.hidden = nativeAd.store ? NO : YES;

  ((UILabel *)adView.priceView).text = nativeAd.price;
  adView.priceView.hidden = nativeAd.price ? NO : YES;

  ((UILabel *)adView.advertiserView).text = nativeAd.advertiser;
  adView.advertiserView.hidden = nativeAd.advertiser ? NO : YES;

  // In order for the SDK to process touch events properly, user interaction
  // should be disabled.
  adView.callToActionView.userInteractionEnabled = NO;

  // Associate the native ad view with the native ad object. This is
  // required to make the ad clickable.
  // Note: this should always be done after populating the ad views.
  adView.nativeAd = nativeAd;

  return adView;
}
@end

برای مثالی از پیکربندی طرح‌بندی GADNativeAdView خود، به NativeAdView.xib مراجعه کنید.

NativeAdFactory خود را ثبت کنید

هر FLTNativeAdFactory باید با یک factoryId ، یک شناسه String منحصر به فرد، در registerNativeAdFactory:factoryId:nativeAdFactory: ثبت شود. factoryId بعداً هنگام نمونه‌سازی یک تبلیغ بومی از کد Dart استفاده خواهد شد.

یک FLTNativeAdFactory می‌تواند برای هر طرح‌بندی تبلیغات بومی منحصر به فرد مورد استفاده توسط برنامه شما پیاده‌سازی و ثبت شود، یا یک طرح‌بندی واحد می‌تواند تمام طرح‌بندی‌ها را مدیریت کند.

پس از ایجاد FLTNativeAdFactory ، AppDelegate خود را به صورت زیر تنظیم کنید:

#import "FLTGoogleMobileAdsPlugin.h"
#import "NativeAdFactoryExample.h"

@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
      didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [GeneratedPluginRegistrant registerWithRegistry:self];

  // Must be added after GeneratedPluginRegistrant registerWithRegistry:self];
  // is called.
  NativeAdFactoryExample *nativeAdFactory = [[NativeAdFactoryExample alloc] init];
  [FLTGoogleMobileAdsPlugin registerNativeAdFactory:self
                                          factoryId:@"adFactoryExample"
                                    nativeAdFactory:nativeAdFactory];

  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end

بارگذاری آگهی

بعد از اینکه کد مخصوص پلتفرم خود را اضافه کردید، برای بارگذاری تبلیغات به Dart مراجعه کنید. مطمئن شوید که factoryID با شناسه‌ای که قبلاً ثبت کرده‌اید مطابقت دارد.

class NativeExampleState extends State<NativeExample> {
  NativeAd? _nativeAd;
  bool _nativeAdIsLoaded = false;

 // TODO: replace this test ad unit with your own ad unit.
 final String _adUnitId = Platform.isAndroid
      ? 'ca-app-pub-3940256099942544/2247696110'
      : 'ca-app-pub-3940256099942544/3986624511';

  /// Loads a native ad.
  void loadAd() {
    _nativeAd = NativeAd(
        adUnitId: _adUnitId,
        // Factory ID registered by your native ad factory implementation.
        factoryId: 'adFactoryExample',
        listener: NativeAdListener(
          onAdLoaded: (ad) {
            print('$NativeAd loaded.');
            setState(() {
              _nativeAdIsLoaded = true;
            });
          },
          onAdFailedToLoad: (ad, error) {
            // Dispose the ad here to free resources.
            print('$NativeAd failedToLoad: $error');
            ad.dispose();
          },
        ),
        request: const AdRequest(),
        // Optional: Pass custom options to your native ad factory implementation.
        customOptions: {'custom-option-1', 'custom-value-1'}
    );
    _nativeAd.load();
  }
}

رویدادهای تبلیغات بومی

برای اطلاع از رویدادهای مربوط به تعاملات تبلیغات بومی، از ویژگی listener مربوط به تبلیغ استفاده کنید. سپس، NativeAdListener را برای دریافت فراخوانی‌های رویداد تبلیغ پیاده‌سازی کنید.

class NativeExampleState extends State<NativeExample> {
  NativeAd? _nativeAd;
  bool _nativeAdIsLoaded = false;

 // TODO: replace this test ad unit with your own ad unit.
 final String _adUnitId = Platform.isAndroid
      ? 'ca-app-pub-3940256099942544/2247696110'
      : 'ca-app-pub-3940256099942544/3986624511';

  /// Loads a native ad.
  void loadAd() {
    _nativeAd = NativeAd(
        adUnitId: _adUnitId,
        // Factory ID registered by your native ad factory implementation.
        factoryId: 'adFactoryExample',
        listener: NativeAdListener(
          onAdLoaded: (ad) {
            print('$NativeAd loaded.');
            setState(() {
              _nativeAdIsLoaded = true;
            });
          },
          onAdFailedToLoad: (ad, error) {
            // Dispose the ad here to free resources.
            print('$NativeAd failedToLoad: $error');
            ad.dispose();
          },
          // Called when a click is recorded for a NativeAd.
          onAdClicked: (ad) {},
          // Called when an impression occurs on the ad.
          onAdImpression: (ad) {},
          // Called when an ad removes an overlay that covers the screen.
          onAdClosed: (ad) {},
          // Called when an ad opens an overlay that covers the screen.
          onAdOpened: (ad) {},
          // For iOS only. Called before dismissing a full screen view
          onAdWillDismissScreen: (ad) {},
          // Called when an ad receives revenue value.
          onPaidEvent: (ad, valueMicros, precision, currencyCode) {},
        ),
        request: const AdRequest(),
        // Optional: Pass custom options to your native ad factory implementation.
        customOptions: {'custom-option-1', 'custom-value-1'}
    );
    _nativeAd.load();
        
  }
}

نمایش آگهی

برای نمایش یک NativeAd به عنوان یک ویجت، باید پس از فراخوانی load() یک AdWidget با یک تبلیغ پشتیبانی‌شده نمونه‌سازی کنید. می‌توانید ویجت را قبل از فراخوانی load() ایجاد کنید، اما load() باید قبل از افزودن آن به درخت ویجت فراخوانی شود.

AdWidget از کلاس Widget در Flutter ارث‌بری می‌کند و می‌تواند مانند هر ویجت دیگری مورد استفاده قرار گیرد. در iOS، مطمئن شوید که ویجت را در یک ظرف با عرض و ارتفاع مشخص قرار می‌دهید. در غیر این صورت، ممکن است تبلیغ شما نمایش داده نشود.

final Container adContainer = Container(
  alignment: Alignment.center,
  child: AdWidget adWidget = AdWidget(ad: _nativeAd!),
  width: WIDTH,
  height: HEIGHT,
);

تبلیغ را دور بریزید

زمانی که دیگر نیازی به دسترسی به یک NativeAd نباشد، باید آن را دور انداخت. بهترین روش برای زمان فراخوانی dispose() پس از حذف AdWidget مرتبط با تبلیغ native از درخت ویجت و در فراخوانی AdListener.onAdFailedToLoad() است.

مراحل بعدی

مثال کامل در گیت‌هاب

پلتفرم بومی