我在Swift iOS项目的视图控制器中实现了一个智能横幅广告,这似乎完美无缺。代码如下:
let bannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
self.view.addSubview(bannerView)
bannerView.delegate = self
bannerView.adUnitID = "ca-app-pub-xyz..."
bannerView.rootViewController = self
let request = GADRequest()
request.testDevices = [kGADSimulatorID, "my-iphone-device-id"]
bannerView.load(request)
我现在想在我项目的另一个视图控制器中做同样的事情。最简单的解决方案是简单地将上面的代码复制粘贴到新的控制器中,这样可以正常工作。
我宁愿不这样做,因为拥有我的iPhone "my-iphone-device-id"
的测试ID字符串的多个副本似乎不是最佳做法。是否有更好的方法来存储此ID,以便我的项目中的所有控制器都可以访问它,而不必将字符串复制粘贴到任何地方?
答案 0 :(得分:1)
在整个应用程序中将此类用于Centralizing AdBanner
。
如何使用
// Set bannerViewAdUnitID = Your Banner Id First in below class
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
SwiftyAd.shared.showBanner(from: self)
}
<强>类强>
//
// SwiftyAd.swift
// AdTest
//
// Created by Satish on 9/3/17.
// Copyright © 2017 Satish. All rights reserved.
//
import GoogleMobileAds
/// LocalizedString (todo)
private enum LocalizedString {
static let sorry = "Sorry"
static let ok = "OK"
static let noVideo = "No video available to watch at the moment."
}
/// SwiftyAdsDelegate
protocol SwiftyAdDelegate: class {
/// SwiftyAd did open
func swiftyAdDidOpen(_ swiftyAd: SwiftyAd)
/// SwiftyAd did close
func swiftyAdDidClose(_ swiftyAd: SwiftyAd)
/// SwiftyAd did reward user
func swiftyAd(_ swiftyAd: SwiftyAd, didRewardUserWithAmount rewardAmount: Int)
}
/**
SwiftyAd
A helper class to manage adverts from AdMob.
*/
final class SwiftyAd: NSObject {
/// Banner position
enum BannerPosition {
case bottom
case top
}
// MARK: - Static Properties
/// Shared instance
static let shared = SwiftyAd()
// MARK: - Properties
/// Delegates
weak var delegate: SwiftyAdDelegate?
/// Remove ads
var isRemoved = false {
didSet {
guard isRemoved else { return }
removeBanner()
}
}
/// Ads
fileprivate var bannerViewAd: GADBannerView?
/// Test Ad Unit IDs. Will get set to real ID in setup method
fileprivate var bannerViewAdUnitID = "***********YOUR ID******"
/// Interval counter
private var intervalCounter = 0
/// Reward amount backup
fileprivate var rewardAmountBackup = 1
/// Banner position
fileprivate var bannerPosition = BannerPosition.bottom
/// Banner size
fileprivate var bannerSize: GADAdSize {
let isLandscape = UIApplication.shared.statusBarOrientation.isLandscape
return isLandscape ? kGADAdSizeSmartBannerLandscape : kGADAdSizeSmartBannerPortrait
}
// MARK: - Init
/// Init
private override init() { }
// MARK: - Show Banner
/// Show banner ad
///
/// - parameter viewController: The view controller that will present the ad.
/// - parameter position: The position of the banner. Defaults to bottom.
func showBanner(from viewController: UIViewController, at position: BannerPosition = .bottom) {
guard !isRemoved else { return }
bannerPosition = position
loadBannerAd(from: viewController)
}
// MARK: - Remove Banner
/// Remove banner ads
func removeBanner() {
print("Removed banner ad")
bannerViewAd?.delegate = nil
bannerViewAd?.removeFromSuperview()
bannerViewAd = nil
}
// MARK: - Update For Orientation
/// Handle orientation chang
func updateOrientation() {
print("AdMob banner orientation updated")
guard let bannerViewAd = bannerViewAd else { return }
bannerViewAd.adSize = bannerSize
setBannerToOnScreenPosition(bannerViewAd, from: bannerViewAd.rootViewController)
}
}
// MARK: - Requesting Ad
private extension SwiftyAd {
/// Load banner ad
func loadBannerAd(from viewController: UIViewController) {
print("AdMob banner ad loading...")
bannerViewAd?.removeFromSuperview()
bannerViewAd = GADBannerView(adSize: bannerSize)
guard let bannerViewAd = bannerViewAd else { return }
bannerViewAd.adUnitID = bannerViewAdUnitID
bannerViewAd.delegate = self
bannerViewAd.rootViewController = viewController
bannerViewAd.isHidden = true
setBannerToOffScreenPosition(bannerViewAd, from: viewController)
viewController.view.addSubview(bannerViewAd)
let request = GADRequest()
#if DEBUG
request.testDevices = [kGADSimulatorID]
#endif
bannerViewAd.load(request)
}
}
// MARK: - GADBannerViewDelegate
extension SwiftyAd: GADBannerViewDelegate {
// Did receive
func adViewDidReceiveAd(_ bannerView: GADBannerView) {
print("AdMob banner did receive ad from: \(bannerView.adNetworkClassName ?? "")")
bannerView.isHidden = false
UIView.animate(withDuration: 1.5) { [weak self] in
self?.setBannerToOnScreenPosition(bannerView, from: bannerView.rootViewController)
}
}
// Will present
func adViewWillPresentScreen(_ bannerView: GADBannerView) { // gets called only in release mode
print("AdMob banner clicked")
delegate?.swiftyAdDidOpen(self)
}
// Will dismiss
func adViewWillDismissScreen(_ bannerView: GADBannerView) {
print("AdMob banner about to be closed")
}
// Did dismiss
func adViewDidDismissScreen(_ bannerView: GADBannerView) { // gets called in only release mode
print("AdMob banner closed")
delegate?.swiftyAdDidClose(self)
}
// Will leave application
func adViewWillLeaveApplication(_ bannerView: GADBannerView) {
print("AdMob banner will leave application")
delegate?.swiftyAdDidOpen(self)
}
// Did fail to receive
func adView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: GADRequestError) {
print(error.localizedDescription)
UIView.animate(withDuration: 1.5 , animations: { [weak self] in
self?.setBannerToOffScreenPosition(bannerView, from: bannerView.rootViewController)
}, completion: { finish in
bannerView.isHidden = true
})
}
}
// MARK: - Banner Positions
private extension SwiftyAd {
func setBannerToOnScreenPosition(_ bannerAd: GADBannerView, from viewController: UIViewController?) {
guard let viewController = viewController else { return }
switch self.bannerPosition {
case .bottom:
bannerAd.center = CGPoint(x: viewController.view.frame.midX, y: viewController.view.frame.maxY - (bannerAd.frame.height / 2))
case .top:
bannerAd.center = CGPoint(x: viewController.view.frame.midX, y: viewController.view.frame.minY + (bannerAd.frame.height / 2))
}
}
func setBannerToOffScreenPosition(_ bannerAd: GADBannerView, from viewController: UIViewController?) {
guard let viewController = viewController else { return }
switch self.bannerPosition {
case .bottom:
bannerAd.center = CGPoint(x: viewController.view.frame.midX, y: viewController.view.frame.maxY + (bannerAd.frame.height / 2))
case .top:
bannerAd.center = CGPoint(x: viewController.view.frame.midX, y: viewController.view.frame.minY - (bannerAd.frame.height / 2))
}
}
}
// MARK: - Alert
private extension SwiftyAd {
func showNoVideoAvailableAlert(from viewController: UIViewController) {
let alertController = UIAlertController(title: LocalizedString.sorry, message: LocalizedString.noVideo, preferredStyle: .alert)
let okAction = UIAlertAction(title: LocalizedString.ok, style: .cancel)
alertController.addAction(okAction)
/*
`Ad` event handlers may be called on a background queue. Ensure
this alert is presented on the main queue.
*/
DispatchQueue.main.async {
viewController.present(alertController, animated: true)
}
}
}
// MARK: - Print
private extension SwiftyAd {
/// Overrides the default print method so it print statements only show when in DEBUG mode
func print(_ items: Any...) {
#if DEBUG
Swift.print(items)
#endif
}
}
答案 1 :(得分:0)
是否有更好的方法来存储此ID,以便我的所有控制器 项目可以访问它,而无需复制粘贴字符串 到处都是吗?
当然有。 Google gives you two options如何请求测试广告。
有两种获取测试广告的方法:
使用Google的示例广告单元之一。
使用您自己的广告单元并启用测试设备。
恕我直言,不要麻烦测试设备ID。只需请求带有示例广告单元的测试广告即可。
添加具有以下内容的 Constants.swift 类:
static var adUnitID: String {
#if DEBUG
return "ca-app-pub-3940256099942544/2934735716"
#else
return "my production ad unit"
#endif
}
并且在您的请求中:
let bannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
bannerView.adUnitID = Constants.adUnitID
我为Google横幅广告指南编写了扩展程序,以动态显示和隐藏横幅,检测连接丢失并使用正确的智能横幅Opon旋转,也许这也有帮助:https://github.com/soenkegissel/ShowAndHideAdBanner