如何在Swift/Xcode/iOS中实现Google AdMob原生模板广告
AdMob原生广告模板接入操作指南
1. Objective-C 代码接入说明
- 首先在你要展示原生广告的ViewController的
.m文件顶部引入模板头文件:
#import "NativeTemplates/GADTSmallTemplateView.h" #import "NativeTemplates/GADTTemplateView.h"
同时确保该ViewController遵循GADUnifiedNativeAdDelegate协议。
- 官方给出的Step2到Step7的代码,全部放到你请求原生广告成功的回调方法中。也就是你调用AdMob的原生广告请求接口,拿到返回的有效
GADUnifiedNativeAd实例的位置,在拿到实例之后执行这段代码即可,不要提前在viewDidLoad等生命周期方法里执行,否则广告还没加载完成会渲染失败。
注意:如果编译提示找不到模板头文件,检查你导入NativeTemplates文件夹时是否勾选了「Copy items if needed」,以及文件夹的目标成员归属是否包含你的主App target。
2. Swift 对应实现逻辑
因为模板是Objective-C编写的,Swift项目需要先配置Objective-C桥接文件,在桥接文件中导入上述两个模板头文件,否则Swift无法识别模板类。如果你的项目之前没有桥接文件,新建一个任意OC文件时Xcode会自动提示创建桥接文件,确认创建后把导入语句加到桥接文件即可。
对应功能的Swift代码如下:
// 初始化模板视图对象 let templateView = GADTSmallTemplateView() templateView.translatesAutoresizingMaskIntoConstraints = false // 绑定原生广告视图和代理 nativeAdView = templateView nativeAd.delegate = self // 将模板添加到你要展示的父视图上 view.addSubview(templateView) // 可选:自定义样式配置,不需要可直接删除本段 let myBlueColor = "#5C84F0" let styles: [AnyHashable: Any] = [ GADTNativeTemplateStyleKeyCallToActionFont: UIFont.systemFont(ofSize: 15), GADTNativeTemplateStyleKeyCallToActionFontColor: UIColor.white, GADTNativeTemplateStyleKeyCallToActionBackgroundColor: GADTTemplateView.color(fromHexString: myBlueColor), GADTNativeTemplateStyleKeySecondaryFont: UIFont.systemFont(ofSize: 15), GADTNativeTemplateStyleKeySecondaryFontColor: UIColor.gray, GADTNativeTemplateStyleKeySecondaryBackgroundColor: UIColor.white, GADTNativeTemplateStyleKeyPrimaryFont: UIFont.systemFont(ofSize: 15), GADTNativeTemplateStyleKeyPrimaryFontColor: UIColor.black, GADTNativeTemplateStyleKeyPrimaryBackgroundColor: UIColor.white, GADTNativeTemplateStyleKeyTertiaryFont: UIFont.systemFont(ofSize: 15), GADTNativeTemplateStyleKeyTertiaryFontColor: UIColor.gray, GADTNativeTemplateStyleKeyTertiaryBackgroundColor: UIColor.white, GADTNativeTemplateStyleKeyMainBackgroundColor: UIColor.white, GADTNativeTemplateStyleKeyCornerRadius: NSNumber(value: 7.0) ] templateView.styles = styles // 给模板绑定已加载成功的原生广告对象 templateView.nativeAd = nativeAd // 可选:自动添加约束,让模板撑满父视图宽度、垂直居中 templateView.addHorizontalConstraintsToSuperviewWidth() templateView.addVerticalCenterConstraintToSuperview()
内容的提问来源于stack exchange,提问作者Sandy
相关产品推荐
相关产品推荐

