From 2d895e5b2f04f13a6342ca91f3ee0b31ef9f382c Mon Sep 17 00:00:00 2001 From: kimkyuchul Date: Sun, 1 Dec 2024 14:36:04 +0900 Subject: [PATCH] [ADD] BKGoogleAdView (#150) --- .../Feature/Scene/Common/BKGoogleAdView.swift | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Projects/Feature/Scene/Common/BKGoogleAdView.swift diff --git a/Projects/Feature/Scene/Common/BKGoogleAdView.swift b/Projects/Feature/Scene/Common/BKGoogleAdView.swift new file mode 100644 index 00000000..a7a6e185 --- /dev/null +++ b/Projects/Feature/Scene/Common/BKGoogleAdView.swift @@ -0,0 +1,63 @@ +// +// BKGoogleAdView.swift +// Feature +// +// Created by kyuchul on 11/30/24. +// Copyright © 2024 com.kyuchul.blink. All rights reserved. +// + +import SwiftUI + +import Services + +import GoogleMobileAds + +struct BKGoogleAdView: UIViewControllerRepresentable { + @Binding private var isPresented: Bool + @Binding private var interstitialAd: GoogleAd? + private let dismissAdScreen: () -> Void + private let viewController: UIViewController + + init(isPresented: Binding, + interstitialAd: Binding, + dismissAdScreen: @escaping () -> Void + ) { + self._isPresented = isPresented + self._interstitialAd = interstitialAd + self.dismissAdScreen = dismissAdScreen + self.viewController = UIViewController() + } + + func makeUIViewController(context: Context) -> UIViewController { + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(1)) { + if let interstitialAd { + interstitialAd.ad.present(fromRootViewController: viewController) + } + } + + return viewController + } + + func updateUIViewController(_ uiViewController: UIViewController, context: Context) {} + + func makeCoordinator() -> Coordinator { + Coordinator(parent: self) + } +} + +extension BKGoogleAdView { + final class Coordinator: NSObject, GADFullScreenContentDelegate { + private let parent: BKGoogleAdView + + init(parent: BKGoogleAdView) { + self.parent = parent + super.init() + parent.interstitialAd?.ad.fullScreenContentDelegate = self + } + + func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) { + parent.isPresented.toggle() + parent.dismissAdScreen() + } + } +}