使用Swift语言显示AdMob应用程序打开的广告可以通过以下步骤实现:
import GoogleMobileAds
class ViewController: UIViewController, GADBannerViewDelegate {
var bannerView: GADBannerView!
override func viewDidLoad() {
super.viewDidLoad()
bannerView = GADBannerView(adSize: kGADAdSizeBanner)
bannerView.adUnitID = "YOUR_AD_UNIT_ID"
bannerView.rootViewController = self
bannerView.delegate = self
let request = GADRequest()
request.testDevices = [kGADSimulatorID] // 在模拟器上测试广告
bannerView.load(request)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let adHeight = bannerView.frame.size.height
let adWidth = bannerView.frame.size.width
let screenWidth = view.frame.size.width
let screenHeight = view.frame.size.height
bannerView.frame = CGRect(x: (screenWidth - adWidth) / 2, y: screenHeight - adHeight, width: adWidth, height: adHeight)
view.addSubview(bannerView)
}
func adViewDidReceiveAd(_ bannerView: GADBannerView) {
print("广告加载成功")
}
func adView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: GADRequestError) {
print("广告加载失败: \(error.localizedDescription)")
}
func adViewWillPresentScreen(_ bannerView: GADBannerView) {
print("广告将要显示全屏广告")
}
func adViewWillDismissScreen(_ bannerView: GADBannerView) {
print("广告将要关闭全屏广告")
}
func adViewDidDismissScreen(_ bannerView: GADBannerView) {
print("广告已关闭全屏广告")
}
func adViewWillLeaveApplication(_ bannerView: GADBannerView) {
print("用户点击广告将离开应用")
}
在上述代码中,需要将"YOUR_AD_UNIT_ID"替换为你在AdMob网站上获取到的广告单元ID。
这样,当应用程序打开时,就会在视图控制器的底部显示一个AdMob广告条。根据需要,你可以根据广告的尺寸和位置进行调整。
推荐的腾讯云相关产品:腾讯广告(https://cloud.tencent.com/product/tga)
领取专属 10元无门槛券
手把手带您无忧上云