我在Xcode上做了一个游戏,并添加了Interstitial Google Ads以便在每次会话结束时(定时1分钟的会话)展示。但是,在每个会话结束时,我都对其进行了编程,因此调用了一个警报,该警报显示了该会话的分数(alertController)。但是,当我在游戏中添加广告时,会话结束后立即调用广告,并且由于某种原因不再调用警报。我要这样做,以便仅在用户关闭警报后才调用广告,这样他们就知道每个会话的得分。这是快捷代码。
import UIKit
import AVFoundation
import GoogleMobileAds
import GameKit
class MainViewController: UIViewController, GADInterstitialDelegate, GKGameCenterControllerDelegate
{
var interstitial: GADInterstitial!
var audioPlayer : AVAudioPlayer!
@IBOutlet weak var number1:UILabel?
@IBOutlet weak var number2:UILabel?
@IBOutlet weak var timeLabel:UILabel?
@IBOutlet weak var scorecounter:UILabel?
@IBOutlet weak var inputField:UITextField?
@IBOutlet weak var highscore:UILabel?
var score:Int = 0
var HighScore:Int = 0
var timer:Timer?
var seconds:Int = 60
let defaults = UserDefaults.standard
override func viewDidLoad()
{
super.viewDidLoad()
authPlayer()
interstitial = createAndLoadInterstitial()
checkForHighScore()
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "sample", ofType: "mp3")!))
audioPlayer.prepareToPlay()
let audioSession = AVAudioSession.sharedInstance()
do{
try audioSession.setCategory(AVAudioSession.Category.playback)
}
catch{
}
}
catch{
print(error)
}
setRandomNumberLabel1()
setRandomNumberLabel2()
updateScoreLabel()
audioPlayer.play()
updateHighScoreLabel()
inputField?.addTarget(self, action: #selector(textFieldDidChange(textField:)), for:UIControl.Event.editingChanged)
}
func createAndLoadInterstitial() -> GADInterstitial {
let interstitial = GADInterstitial(adUnitID: "ca-app-pub-6077290479224437/4962653070")
interstitial.delegate = self
interstitial.load(GADRequest())
return interstitial
}
func interstitialDidDismissScreen(_ ad: GADInterstitial) {
interstitial = createAndLoadInterstitial()
}
func updateScoreLabel()
{
scorecounter?.text = "\(score)"
}
func updateHighScoreLabel()
{
highscore?.text = "\(HighScore)"
if(score >= HighScore){
HighScore = score
saveHighScore()
}
}
func updateTimeLabel()
{
if(timeLabel != nil)
{
let min:Int = (seconds / 60) % 60
let sec:Int = seconds % 60
let min_p:String = String(format: "%02d", min)
let sec_p:String = String(format: "%02d", sec)
timeLabel!.text = "\(min_p):\(sec_p)"
}
}
func setRandomNumberLabel1()
{
number1?.text = generateRandomString1()
}
func setRandomNumberLabel2()
{
number2?.text = generateRandomString2()
}
@objc func textFieldDidChange(textField:UITextField)
{
if inputField?.text?.count ?? 0 < 2
{
return
}
if let number1_text = number1?.text,
let number2_text = number2?.text,
let input_text = inputField?.text,
let number1 = Int(number1_text),
let number2 = Int(number2_text),
let input = Int(input_text)
{
print("Comparing: \(input_text) == \(number1_text) times \(number2_text)")
if(input == number1 * number2)
{
print("Correct!")
score += 1
inputField?.text = ""
updateHighScoreLabel()
saveHighScore()
}
else
{
print("Incorrect!")
inputField?.text = ""
}
}
setRandomNumberLabel1()
setRandomNumberLabel2()
updateScoreLabel()
updateHighScoreLabel()
if(timer == nil)
{
timer = Timer.scheduledTimer(timeInterval: 1.0, target:self, selector:#selector(onUpdateTimer), userInfo:nil, repeats:true)
}
}
@objc func onUpdateTimer() -> Void
{
if(seconds > 0 && seconds <= 60)
{
seconds -= 1
updateTimeLabel()
}
else if(seconds == 0)
{
if(timer != nil)
{
timer!.invalidate()
timer = nil
var alertController = UIAlertController(title: "Time's Up!", message: "You got a score of \(score) points. Good Job!", preferredStyle: .alert)
if score == HighScore{
alertController = UIAlertController(title: "New High Score!", message: "You scored a new high score of \(score) points! Keep it Up!", preferredStyle: .alert)
}
if interstitial.isReady {
interstitial.present(fromRootViewController: self)
}
let restartAction = UIAlertAction(title: "Restart", style: .default, handler: nil)
alertController.addAction(restartAction)
self.present(alertController, animated: true, completion: nil)
score = 0
seconds = 60
updateTimeLabel()
updateScoreLabel()
setRandomNumberLabel1()
setRandomNumberLabel2()
}
}
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
@IBAction func CallGC(sender: AnyObject){
leaderhighscore(number: HighScore)
showLeaderBoard()
}
func authPlayer(){
let localPlayer = GKLocalPlayer.local
localPlayer.authenticateHandler = {
(view, error) in
if view != nil {
self.present(view!, animated: true, completion: nil)
}
else{
print(GKLocalPlayer.local.isAuthenticated)
}
}
}
@IBAction func Pause(sender: AnyObject){
if audioPlayer.isPlaying{
audioPlayer.pause()
}
else{
}
}
@IBAction func Play(sender: AnyObject){
audioPlayer.play()
}
func generateRandomString1() -> String
{
var result:String = ""
for _ in 1...1
{
let digit = Int.random(in: 2..<9)
result += "\(digit)"
}
return result
}
func generateRandomString2() -> String
{
var result:String = ""
for _ in 1...1
{
let digit = Int.random(in: 5..<13)
result += "\(digit)"
}
return result
}
func saveHighScore()
{
defaults.set(HighScore, forKey: "savedScore")
}
func checkForHighScore(){
let savedScore = defaults.integer(forKey: "savedScore")
HighScore = savedScore
}
func leaderhighscore(number : Int){
if GKLocalPlayer.local.isAuthenticated{
let scoreReporter = GKScore(leaderboardIdentifier: "MinuteMath")
scoreReporter.value = Int64(number)
let scoreArray : [GKScore] = [scoreReporter]
GKScore.report(scoreArray, withCompletionHandler: nil)
}
}
func showLeaderBoard(){
let viewController = self.view.window?.rootViewController
let gcvc = GKGameCenterViewController()
gcvc.gameCenterDelegate = self
viewController?.present(gcvc, animated: true, completion: nil)
}
func gameCenterViewControllerDidFinish(_ gameCenterViewController: GKGameCenterViewController) {
gameCenterViewController.dismiss(animated: true, completion: nil)
}
}