我一直在尝试弄清楚如何在我的 Xamarin.iOS 应用程序中实现原生谷歌广告 (admob)。 (不是 xamarin 形式)
我疯狂地用谷歌搜索,但找不到任何好的例子。
有人有可以分享的代码吗?
这是我到目前为止的代码,但 adloader.delegate 始终为空..
public partial class ExploreController : UIViewController
{
readonly AdLoader adLoader;
public ExploreController (IntPtr handle) : base (handle)
{
adLoader = new AdLoader(
"ca-app-pub-3940256099942544/3986624511",
this,
new AdLoaderAdType[] { AdLoaderAdType.Native },
new AdLoaderOptions[] { new AdLoaderOptions() });
adLoader.Delegate = new MyAdLoaderDelegate();
var request = Request.GetDefaultRequest();
}
}
public class MyAdLoaderDelegate : NSObject, IUnifiedNativeAdLoaderDelegate
{
public MyAdLoaderDelegate()
{
}
public void DidReceiveUnifiedNativeAd(AdLoader adLoader, NativeAd nativeAd)
{
Debug.WriteLine("DidReceiveUnifiedNativeAd");
}
public void DidFailToReceiveAd(AdLoader adLoader, NSError error)
{
Debug.WriteLine("DidFailToReceiveAd");
//base.DidFailToReceiveAd(adLoader, error);
}
public void DidFinishLoading(AdLoader adLoader)
{
Debug.WriteLine("DidFinishLoading");
//base.DidFinishLoading(adLoader);
}
}
此解决方案适用于具有本机
Xamarin
的 Storyboard
iOS 应用程序。这是不是 Xamarin Forms 项目。
安装NuGet包
Xamarin.Google.iOS.MobileAds
(最新)
您应该为横幅提供 UIView,并具有所有所需的约束(您在
XCode
中编辑 Storyboard 文件):
GADBannerView
:注意: 您在 Storyboard 中使用本机名称
GADBannerView
,而在 C# 中,您引用与 BannerView
相同的类。
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
BannerView bottomBanner { get; set; }
现在您应该能够从 C# 代码引用您的原生 AdMob 横幅。这是加载广告的方式:
public void ShowBannerAd()
{
bottomBanner.RootViewController = this;
bottomBanner.AdSize = AdSizeCons.Banner;
bottomBanner.AdUnitId = "<YOUR_AD_UNIT_ID>";
var request = Request.GetDefaultRequest();
bottomBanner.LoadRequest(request);
}
结果: