Skip to content

wayne90040/GoogleAds

Repository files navigation

GoogleAds

This is a quick tutorial on using the Google Mobile Ads SDK with SwiftUI.

Installation

Swift Package Manager

dependencies: [
    .package(url: "httpshttps://github.com/wayne90040/GoogleAds")
]

Usage

Please refer to Google's quick start guide to complete the preliminary info.plist setup.

Initialize the Mobile Ads SDK

@main
struct MainApp: App {
    init() {
       GoogleAds.register() 
    }
    
    var body: some Scene { 
        ...
    }
}

Banner

AdsBanner(id: "ca-app-pub-3940256099942544/2934735716", size: .normal)

Interstitial

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")
        }
    }
}

Native

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: "")
    }
}

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages