Xamarin.Forms中的原生Admob广告。是否有任何现成的解决方案/示例?

时间:2018-10-03 09:43:45

标签: xamarin.forms xamarin.ios xamarin.android admob ads

我需要在Xamarin.Forms中实现原生广告。但是我在Xamarin.Forms上找不到任何示例。 也许有人举个例子在Xamarin.Forms上使用原生广告并可以共享。

我试图做的事的例子:

Android:

[assembly: Dependency(typeof(NativeAd))]
namespace Ads.Droid.Platform.Renderers.Ad
{
    public class NativeAd : AdListener, INativeAd
    {
        Context context = Android.App.Application.Context;
        NativeExpressAdView mAdView;

       public void Show()
        {   
            var videoOptions = new VideoOptions.Builder().SetStartMuted(false).Build();
            var adOptions = new NativeAdOptions.Builder().SetVideoOptions(videoOptions).Build();
            AdLoader adLoader = new AdLoader.Builder(context, "ca-app-pub-3940256099942544/2247696110").WithNativeAdOptions(adOptions).Build();

            var request = new AdRequest.Builder();
            foreach (var item in TestDevice.GetTestDevices())
                request.AddTestDevice(item);

            adLoader.LoadAd(request.Build());   
        }
    }
}

或:

[assembly: Dependency(typeof(NativeAd))]
namespace Ads.Droid.Platform.Renderers.Ad
{
    public class NativeAd : AdListener, INativeAd
    {
        NativeExpressAdView mAdView;

       public void Show()
        {   
            mAdView = new NativeExpressAdView(Android.App.Application.Context)
            {
                AdUnitId = "ca-app-pub-3940256099942544/2247696110",
                AdSize = AdSize.MediumRectangle
            };
            var request = new AdRequest.Builder();
            foreach (var item in TestDevice.GetTestDevices())
                request.AddTestDevice(item);
            mAdView.LoadAd(request.Build());    
        }
    }
}

在iOS中没有这样做,但我还需要一个示例。 也许有些事情需要改变或完成。 请帮助我。

1 个答案:

答案 0 :(得分:0)

您还可以在iOS中使用GoogleMobileAds。来自NuGet的Xamarin.Firebase.iOS.AdMob软件包很重要。

  

在AppDelegate.cs

...
using Google.MobileAds;
...

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
   . . .
   MobileAds.Configure("ca-app-pub-3940256099942544/2247696110 ");
   . . . 
} 
  

在iOS依赖项中

[assembly: Xamarin.Forms.Dependency(typeof(NativeiOSAd))]
namespace XXX.iOS
{
    public class NativeiOSAd:NativeAd
    {

        NativeExpressAdView mAdView;

        public NativeiOSAd()
        {
        }

        public void Show()
        {
            AdSize adSize = new AdSize();
            adSize.Size = new CGSize(UIScreen.MainScreen.Bounds.Size.Width, 100);

            mAdView = new NativeExpressAdView(adSize)
            {
                AdUnitID = "ca-app-pub-3940256099942544/2247696110"
            };

            Request request = Request.GetDefaultRequest();


            mAdView.LoadRequest(request);
        }
    }
}

请不要忘记在应用的Info.plist文件中添加NSAllowsArbitraryLoadsNSAllowsArbitraryLoadsForMediaNSAllowsArbitraryLoadsInWebContent异常以禁用ATS限制。

enter image description here