要在SwiftUI中使用Admob原生广告,你需要遵循以下步骤:
Google-Mobile-Ads-SDK
依赖项。在你的项目的Package.swift
文件中添加以下内容:dependencies: [
.package(url: "https://github.com/googleads/googleads-mobile-ios-swift.git", from: "8.15.0")
]
然后运行swift package update
。
GoogleMobileAds
框架:import GoogleMobileAds
struct NativeAdView: UIViewRepresentable {
func makeUIView(context: Context) -> GADNativeAdView {
let nativeAdView = GADNativeAdView()
// 配置原生广告视图
return nativeAdView
}
func updateUIView(_ uiView: GADNativeAdView, context: Context) {}
}
struct ContentView: View {
@State private var nativeAd: GADNativeAd?
var body: some View {
VStack {
if let nativeAd = nativeAd {
NativeAdView(nativeAd: nativeAd)
} else {
Text("Loading ad...")
}
}
.onAppear {
loadNativeAd()
}
}
private func loadNativeAd() {
let adLoader = GADAdLoader(adUnitID: "your_ad_unit_id", rootViewController: UIApplication.shared.windows.first?.rootViewController ?? UIViewController(), adTypes: [.native], options: nil)
adLoader.load(GADRequest()) { [weak self] (adLoaderResult) in
switch adLoaderResult {
case .success(let adLoaderResponse):
if let nativeAd = adLoaderResponse.loadedAds.first {
self?.nativeAd = native(示例代码,需要根据实际情况修改)
}
case .failed(let error):
print("Failed to load native ad with error: \(error.localizedDescription)")
}
}
}
}
<key>GADApplicationIdentifier</key>
<string>your_admob_app_id</string>
领取专属 10元无门槛券
手把手带您无忧上云