iosswiftadmobmessagekit

Add Admob banner to messagekit


how can I add admob banner to messageviewcontroller of messagekit?

I have tried. The ad is loaded but it not visible.

I would like to add the banner to the top of view.

Please help.

final class ChatViewController: MessagesViewController, MessagesDataSource {

override func viewDidLoad() {
    messagesCollectionView = MessagesCollectionView(frame: .zero, collectionViewLayout: CustomMessagesFlowLayout())
    messagesCollectionView.register(CustomMessageKitCell.self)
    // In this case, we instantiate the banner with desired ad size.
    bannerView = GADBannerView(adSize: kGADAdSizeBanner)

    bannerView.adUnitID = "ca-app-pub-40..."
    bannerView.rootViewController = self
    bannerView.load(GADRequest())
    bannerView.delegate = self
    addBannerViewToView(bannerView)
    ...
}

var bannerView: GADBannerView!

func addBannerViewToView(_ bannerView: GADBannerView) {
 bannerView.translatesAutoresizingMaskIntoConstraints = false
 view.addSubview(bannerView)
 view.addConstraints(
   [NSLayoutConstraint(item: bannerView,
                       attribute: .top,
                       relatedBy: .equal,
                       toItem: view.safeAreaLayoutGuide,
                       attribute: .top,
                       multiplier: 1,
                       constant: 0),
    NSLayoutConstraint(item: bannerView,
                       attribute: .centerX,
                       relatedBy: .equal,
                       toItem: view,
                       attribute: .centerX,
                       multiplier: 1,
                       constant: 0)
   ])
}
...
}

Solution

  • You need to call super.viewDidLoad() before you add any subviews (I'm not seeing if you even call it at all but it might be in the ... at the end). MessageKit uses viewDidLoad to add the MessagesCollectionView into the view hierarchy and so if you call super after, then your banner view will be underneath the MessagesCollectionView. In this case since you're instantiating a MessagesCollectionView with a custom layout you'll want to call super after instantiating that view but before adding any subviews like this:

    override func viewDidLoad() {
        messagesCollectionView = MessagesCollectionView(frame: .zero, collectionViewLayout: CustomMessagesFlowLayout())
        super.viewDidLoad() // <-- Add this
        messagesCollectionView.register(CustomMessageKitCell.self)
        // In this case, we instantiate the banner with desired ad size.
        bannerView = GADBannerView(adSize: kGADAdSizeBanner)
    
        bannerView.adUnitID = "ca-app-pub-40..."
        bannerView.rootViewController = self
        bannerView.load(GADRequest())
        bannerView.delegate = self
        addBannerViewToView(bannerView)
        ...
    }