Connected advertising from Yandex to my application on SwiftUI. Ads are shown only in the ContentView. When you switch to another view in the logs, you can see that the ad is loading, but for some reason it is not shown. Here is my code.
YandexAd.swift file:
import Foundation
import YandexMobileAds
import UIKit
// Yandex
class InterstitialYandex: NSObject, YMAInterstitialAdDelegate {
var interstitialYandexAd: YMAInterstitialAd?
override init() {
super.init()
loadInterstitial()
}
func loadInterstitial(){
self.interstitialYandexAd = YMAInterstitialAd(adUnitID: "R-M-2248734-1")
self.interstitialYandexAd?.load()
self.interstitialYandexAd?.delegate = self
}
func interstitialAdDidLoad(_ interstitialYandexAd: YMAInterstitialAd) {
let scenes = UIApplication.shared.connectedScenes
let windowScene = scenes.first as? UIWindowScene
let window = windowScene?.windows.first
let root = window?.rootViewController
//let root = UIApplication.shared.windows.first?.rootViewController
self.interstitialYandexAd?.present(from: root!)
print("Loaded Adv.")
}
func interstitialAdDidFail(toLoad interstitialYandexAd: YMAInterstitialAd, error: Error) {
print("Loading failed. Error: \(error)")
}
func interstitialAdDidFail(toPresent interstitialAd: YMAInterstitialAd, error: Error) {
print("Presenting failed. Error: \(error)")
}
}
And this is how I call it in ContentView and in other views:
ContentView.swift:
import SwiftUI
import AppTrackingTransparency
import AdSupport
import YandexMobileAds
import UIKit
struct ContentView: View {
//Yandex
var interstitialYandex:InterstitialYandex
init() {
self.interstitialYandex = InterstitialYandex()
}
}
IstoriaHome.swift:
import SwiftUI
import YandexMobileAds
import UIKit
struct IstoriyaGameHome: View {
//Yandex
var interstitialYandex:InterstitialYandex
init() {
self.interstitialYandex = InterstitialYandex()
}
}
SwiftUI is off-topic for these forums, this is for discussion of the Swift language itself.
That said, SwiftUI views are structs and they are init'd frequently, at a frequency determined entirely by SwiftUI.
Your InterstitialYandex should be an ObservableObject and be linked to your view's identity by changing
struct ContentView: View {
var interstitialYandex:InterstitialYandex
init() {
self.interstitialYandex = InterstitialYandex()
}
}
to
struct ContentView: View {
@StateObject private var interstitialYandex = InterstitialYandex()
}
This will ensure there's only one instance of this thing created the first time your view is added to the hierarchy, and its lifetime will be tied to the view's lifetime.
I'd recommend this talk for an explanation of all the different @[State|Observed|Environment]Object property wrappers work.
And the docs for StateObject are pretty good:
1 Like