2015-09-25 42 views
0

我曾經說過,當用戶點擊一個按鈕時,它會顯示插頁式廣告,但我不想那樣。我希望如果用戶使用應用程序1分鐘那麼它會自動顯示廣告,並且在用戶關閉廣告之後它會在一段時間後出現。添加計時器以接收iAd插頁式廣告(Xcode,swift)

這裏是我的與按鈕的代碼

var interAd = ADInterstitialAd() 
var interAdView:UIView = UIView() 

var closeButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton 


override func viewDidLoad() { 
    super.viewDidLoad() 

    closeButton.frame = CGRectMake(10, 10, 20, 20) 
    closeButton.layer.cornerRadius = 10 
    closeButton.setTitle("X", forState: .Normal) 
    closeButton.setTitleColor(UIColor.blackColor(), forState: .Normal) 
    closeButton.backgroundColor = UIColor.whiteColor() 
    closeButton.layer.borderColor = UIColor.blackColor().CGColor 
    closeButton.layer.borderWidth = 1 
    closeButton.addTarget(self, action: "close:", forControlEvents: UIControlEvents.TouchDown) 
    } 
    func close(sender: UIButton) { 
    closeButton.removeFromSuperview() 
    interAdView.removeFromSuperview() 

} 

func loadAd() { 
    println("load Ad") 
    interAd = ADInterstitialAd() 
    interAd.delegate = self 

} 

func interstitialAdDidLoad(interstitialAd: ADInterstitialAd!) { 
    println("ad did load") 

    interAdView = UIView() 
    interAdView.frame = self.view.bounds 
    view.addSubview(interAdView) 

    interAd.presentInView(interAdView) 
    UIViewController.prepareInterstitialAds() 

    interAdView.addSubview(closeButton) 
} 
    func interstitialAdDidUnload(interstitialAd: ADInterstitialAd!) { 
    println("ad did not load") 
} 

    func interstitialAd(interstitialAd: ADInterstitialAd!, didFailWithError error: NSError!) { 
    println("failed to recieve") 
    println(error.localizedDescription) 

    closeButton.removeFromSuperview() 
    interAdView.removeFromSuperview() 
} 

@IBAction func ShowAds(sender: UIButton) { 
    loadAd() 

} 
+0

當用戶載入應用程序時,廣告只會顯示一次? –

+0

是的,我想要那樣的東西@dharmeshkheni –

回答

1

兩種方式來實現您的要求。

第一:

您可以使用GCD:

override func viewDidLoad() { 
    super.viewDidLoad() 
    let triggerTime = (Int64(NSEC_PER_SEC) * 60) // set delay you time here. 
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), {() -> Void in 
     self.loadAd() 
    }) 
} 

二:

您可以使用NSTimer

override func viewDidLoad() { 
    super.viewDidLoad() 
    NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(60), target: self, selector: "loadAd", userInfo: nil, repeats: false) 
} 

設定重複parame如果您不想再重複一次,則可以到false

+0

你能解釋我第二種方法嗎?在什麼時候它會來?@dharmeshkheni –

+0

60秒後它會調用'loadAd'方法。 –

+0

還有一件事我不想讓廣告通過點擊按鈕出現。我希望它自動顯示 –