ios - 在每 x 次加载 viewdidload 时显示插页式广告

标签 ios swift uiviewcontroller admob uikit

我想弄清楚,在每 x 次加载 viewdidload 调用时显示一个插页式广告。 当我的 viewdidload 调用时,我正在加载该广告。但是我想加载它,当viewdidload调用x的时候。 任何帮助将不胜感激。这是我的代码;

    class DetailController: UIViewController, GADInterstitialDelegate {

    //Admob
    ...
    ...
    var fullScreenAds : GADInterstitial!

    //Interstitial-Ad
    func createAndLoadInterstitial() -> GADInterstitial? {
        fullScreenAds = GADInterstitial(adUnitID: myInterstitialID)
        guard let fullScreenAds = fullScreenAds else {
            return nil
        }
        let request = GADRequest()
        request.testDevices = [ kGADSimulatorID ]
        fullScreenAds.load(request)
        fullScreenAds.delegate = self

        return fullScreenAds
    }

    func interstitialDidReceiveAd(_ ad: GADInterstitial) {
        print("Ads loaded.")
        ad.present(fromRootViewController: self)
    }

    func interstitialDidFail(toPresentScreen ad: GADInterstitial) {
        print("Ads not loaded.")
    }

    //MARK: View functions
    override func viewDidLoad() {
        super.viewDidLoad()

        ......

        SVProgressHUD.show()
        imageView.af_setImage(withURL: URL(string: pic.largeImageURL!)!, placeholderImage: imgPlaceHolder, filter: nil, progress: nil, progressQueue: DispatchQueue.main, imageTransition: .crossDissolve(0.2), runImageTransitionIfCached: true) { (data) in
            SVProgressHUD.dismiss()
        }

        scrollView.delegate = self
        setupScrollView()
        setupGestureRecognizers()
        setupBanner()

        self.fullScreenAds = createAndLoadInterstitial()
    }
}

最佳答案

你可以使用 UserDefaults每次加载 View 时存储一个计数。达到限制后,重置计数并展示广告。

示例代码:

class ViewController: UIViewController {

    private let adFrequency = 5
    private let userDefaults: UserDefaults = .standard
    private let defaultsKey = "passwordScreenViewCount"

    override func viewDidLoad() {
        super.viewDidLoad()

        let count = userDefaults.integer(forKey: defaultsKey)
        if count + 1 >= adFrequency {
            userDefaults.set(0, forKey: defaultsKey)
            // show the ad
        } else {
            userDefaults.set(count + 1, forKey: defaultsKey)
        }
    }
}

关于ios - 在每 x 次加载 viewdidload 时显示插页式广告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53702765/

相关文章:

ios - 如何快速制作形状

ios - swift 3 : Can't connect to peripheral via BLE

ios - self.tableView 为零,与调用 numberOfSections TableView 的 uitableview 不同

ios - 当以编程方式设置 View Controller 时,UINavigationController 不显示下一步按钮

ios - Xcode 自动布局约束错误

iphone UIView - 加载 View 时收到通知?

ios - 我想在应用程序用户关闭套接字后立即检测断开连接事件

swift - 删除 PencilKit 中的内容

swift - 表节标题 : multi-line/word wrapping

ios - 从 UIViewController 调用 WKInterfaceController 的方法