iOS Interstitial Example

In the example below, an interstitial ad is displayed when the menu item is clicked. When the ad status changes, the snackbar is displayed with the corresponding message.

In a real application, you could use any of the InterstitialAdManager.Event values (.dismissed, .displayError or .timeout) to trigger navigation to another screen.

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

struct MyView: View {
    @StateObject private var adManager = InterstitialAdManager(code: "<zone_code>")
    @State private var isAlertPresented = false
    @State private var alertMessage = ""

    var body: some View {
        NavigationStack {
            ScrollView {
                VStack {
                    // ...

                    Button("Show interstitial ad") {
                        adManager.showAd()
                    }
                    .alert(alertMessage, isPresented: $isAlertPresented) {
                        Button("OK", role: .cancel) { }
                    }

                    // ...
                }
            }
        }
        .onChange(of: adManager.lastEvent) { newEvent in
            guard let event = newEvent else { return }

            switch event {
            case .dismissed:
                alertMessage = "Interstitial ad dismissed"
            case .error:
                alertMessage = "Interstitial ad failed to display"
            case .timeout:
                alertMessage = "Interstitial ad load timeout"
            }

            isAlertPresented = true
            adManager.lastEvent = nil
        }
    }
}