I wanted to prepare helper class for Admob to manage Banner ads. I set the delegate But bannerViewDidReceiveAd method not called. Do you know what could be issue?
protocol BannerAdsManagerProtocol: AnyObject {
func bannerDidReceiveAd(bannerView: GADBannerView)
}
class BannerAdsManager: NSObject {
var bannerView: GADBannerView!
weak var delegate: BannerAdsManagerProtocol?
var rootViewController: UIViewController
init(rootViewController: UIViewController, delegate: BannerAdsManagerProtocol?) {
self.rootViewController = rootViewController
self.delegate = delegate
}
func loadAd(with unitId: String, adSize: GADAdSize) {
self.bannerView = GADBannerView(adSize: adSize)
self.bannerView.adUnitID = unitId
self.bannerView.rootViewController = rootViewController
self.bannerView.delegate = self
let request = GADRequest()
self.bannerView.load(request)
}
}
extension BannerAdsManager: GADBannerViewDelegate {
func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
print(#function)
delegate?.bannerDidReceiveAd(bannerView: bannerView)
}
func bannerView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: Error) {
print(error.localizedDescription)
}
}`
This is how I use to receive bannerView in my ViewController.
override func viewDidLoad() {
super.viewDidLoad()
let bannerAdsManager = BannerAdsManager(rootViewController: self,
delegate: self)
bannerAdsManager.loadAd(with: adId, adSize: GADAdSizeLargeBanner)
)
}
extension ListViewController: BannerAdsManagerProtocol {
func bannerDidReceiveAd(bannerView: GADBannerView) {
addBannerViewToView(bannerView, attritube: .bottom)
}
}
BannerAdsManager
gets deallocated as soon as viewDidLoad
has finished.
You need to store it somewhere outside of the function.
For example, change your viewcontroller to this:
class ListViewController: UIViewController {
var bannerAdsManager: BannerAdsManager!
override func viewDidLoad() {
super.viewDidLoad()
bannerAdsManager = BannerAdsManager(rootViewController: self,
delegate: self)
bannerAdsManager.loadAd(with: adId, adSize: GADAdSizeLargeBanner)
}
}
extension ListViewController: BannerAdsManagerProtocol {
func bannerDidReceiveAd(bannerView: GADBannerView) {
addBannerViewToView(bannerView, attritube: .bottom)
}
}
(I assumed your viewcontroller is named "ListViewController" and you wanted the extension to conform to your protocol.)
There may be more issues, that's all I could get from the given code.