简体   繁体   中英

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)
   ])
}
...
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM