- 首先,需要在项目中导入 Admob SDK。可以使用 CocoaPods 或手动下载和导入 SDK。
- 在项目的 Info.plist 文件中添加 Admob 应用程序 ID。
- 引入 GoogleMobileAds 库并创建一个广告单元 ID。
import SwiftUI
import GoogleMobileAds
final class AdmobRewarded: NSObject, GADRewardedAdDelegate {
private var rewardedAd: GADRewardedAd?
func loadAd() {
GADRewardedAd.load(
withAdUnitID: "",
request: GADRequest(),
completionHandler: { [weak self] ad, error in
guard let self = self else { return }
if let error = error {
print("Rewarded ad failed to load with error: \(error.localizedDescription)")
return
}
self.rewardedAd = ad
self.rewardedAd?.fullScreenContentDelegate = self
}
)
}
func showAd() {
if let ad = rewardedAd {
ad.present(fromRootViewController: UIApplication.shared.windows.first?.rootViewController ?? UIViewController())
} else {
print("The rewarded ad wasn't ready yet.")
}
}
func rewardedAd(_ rewardedAd: GADRewardedAd, userDidEarn reward: GADAdReward) {
print("Reward received with currency: \(reward.type), amount \(reward.amount).")
}
func rewardedAdDidDismissFullScreenContent(_ rewardedAd: GADRewardedAd) {
self.loadAd()
}
}
- 在 ContentView 中创建一个 AdmobRewarded 实例,并调用 loadAd() 和 showAd() 方法以在需要时显示激励广告。
struct ContentView: View {
let rewardedAd = AdmobRewarded()
var body: some View {
VStack {
Text("Hello, World!")
Button("Show rewarded ad") {
rewardedAd.showAd()
}
}
.onAppear {
rewardedAd.loadAd()
}
}
}