This is a quick tutorial on using the Google Mobile Ads SDK with SwiftUI.
dependencies: [
.package(url: "httpshttps://github.com/wayne90040/GoogleAds")
]
Please refer to Google's quick start guide to complete the preliminary info.plist
setup.
@main
struct MainApp: App {
init() {
GoogleAds.register()
}
var body: some Scene {
...
}
}
AdsBanner(id: "ca-app-pub-3940256099942544/2934735716", size: .normal)
extension AdsInterstitial {
func loadAds() async {
do {
try await loadAds(id: "")
}
catch {
debugPrint("")
}
}
}
struct CreateView: View {
private let ads = AdsInterstitial()
var body: some View {
...
.onAppear {
Task {
await ads.loadAds(ads: "ca-app-pub-3940256099942544/4411468910")
}
}
}
private var nextPageButton: some View {
Button {
try? ads.showAd()
isNextPageActive.toggle()
} label: {
Text("Next Page")
}
}
}
Download NativeAdView
, and design it.
struct EXNativeAdsView: View {
private let viewModel = AdsNativeViewModel()
private let xib = Bundle.main.loadNibNamed(
"NativeAdView",
owner: nil,
options: nil)?.first as! GADNativeAdView
var body: some View {
AdsNativeView(viewModel: viewModel, adView: xib)
.onAppear {
viewModel.refresh()
}
}
}
extension AdsNativeViewModel {
func refresh() {
refresh(unitId: "")
}
}