본문 바로가기
iOS

[SwiftUI] Admob 전면 광고(Interstitial ad) 보여주기

by 워뇨옹2 2022. 9. 28.
728x90
반응형

이전 포스팅에 간단하게 광고를 설정하는 방법을 적어놨으니 확인바랍니다.

final class Interstitial: NSObject, GADFullScreenContentDelegate {
    let adUnitID = "ca-app-pub-6235545617614297/1320470587"
    private var interstitial: GADInterstitialAd?
    
    override init() {
        super.init()
        loadInterstitial()
    }
    
    func loadInterstitial(){
        let request = GADRequest()
        GADInterstitialAd.load(withAdUnitID:adUnitID,
                                    request: request,
                          completionHandler: { [self] ad, error in
                            if let error = error {
                              print("Failed to load interstitial ad: \(error.localizedDescription)")
                              return
                            }
                            interstitial = ad
                            interstitial?.fullScreenContentDelegate = self
                          }
        )
    }
    
    /// Tells the delegate that the ad failed to present full screen content.
    func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
        print("Ad did fail to present full screen content.")
    }
    
    /// Tells the delegate that the ad dismissed full screen content.
    func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
        print("Ad did dismiss full screen content.")
        loadInterstitial()
    }
    
    func showAd(){
        let root = UIApplication.shared.windows.first?.rootViewController
        interstitial?.present(fromRootViewController: root!)
    }
}

내 경우에는 Extension이나 Manager 같은 폴더를 하나 만들고 그 안에 GoogleAdManager.swift 파일을 만들어 전체적인 광고모듈을 넣어놓고 관리한다.

 

위 코드도 별도의 swift파일을 생성해서 만들어놓으면 추후에 관리하기 편할 것이다.

 

그 후에 View단에서 가져다 쓰기만 하면 된다.

 

struct ContentView: View {
    let interstitial = Interstitial()
    var body: some View {
        Button {
            interstitial.showAd()
        }, label: {
            Text("Show Ad")
        }
    }
}
728x90
반응형