iOS App-Open Example

In the example below, a full-screen ad is displayed when the app is launched or foregrounded.

final class InterstitialAdManager: NSObject, ObservableObject, FuseFullScreenAdViewDelegate {
    enum Event: Equatable {
        case dismissed
        case error
        case timeout
    }

    @Published var lastEvent: Event? = nil
    private let ad: FuseFullScreenAdView

    init(code: String) {
        ad = FuseFullScreenAdView(code: code)
        ad.delegate = self
    }

    func showAd() {
        ad.show()
    }

    func onEvent(adView: FuseFullScreenAdView, event: FuseAdViewEvent) {
        switch (event) {
        case .dismissed: self.lastEvent = .dismissed
        case .displayTimeout: self.lastEvent = .timeout
        case .displayError: self.lastEvent = .error
        default: break
        }
    }
}

@main
struct iosApp: App {
    @StateObject private var adManager = InterstitialAdManager(code: "<zone_code>")

    var body: some Scene {
        WindowGroup {
            MainView()
                // Display ad on app foregrgound with 1 second display timeout
                .onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { _ in
                    adManager.showAd(timeout: 1)
                }
                // Listen to app open ad events
                .onChange(of: adManager.lastEvent) { newEvent in
                    guard let event = newEvent else { return }

                    let message: String
                    switch event {
                    case .dismissed:
                        message = "ad dismissed"
                    case .error:
                        message = "ad failed to display"
                    case .timeout:
                        message = "ad load timeout"
                    }

                    FuseLoggingUtil.debug("The full-screen ad event: \(message)")
                    adManager.lastEvent = nil
                }
        }
    }
}