在每x个Viewdidload负载中展示插页式广告

时间:2018-12-10 09:30:46

标签: 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()
    }
}

2 个答案:

答案 0 :(得分:3)

每次加载视图时,您都可以使用UserDefaults存储计数。达到上限后,请重置计数并显示广告。

示例代码:

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

答案 1 :(得分:1)

采用1个全局变量viewDidLoadCount并将其设置为0。

假设您要每5 viewDidLoad()展示一次广告。因此,

在每种viewDidLoadCount方法中将viewDidLoad()递增1并检查

//获取全局变量

var viewDidLoadCount : Int = 0
override func viewDidLoad() {
    super.viewDidLoad()

    viewDidLoadCount+=1
    if viewDidLoadCount == 5 {
        //send post notification to your main viewcontroller in which you have done code of ad delegate.
    }
}