我正在尝试实现一个分数,在用户观看激励视频广告后,分数将增加 1。我的代码将分数增加 1,但在我更改 View 并返回到分数的 View 后如图所示,分数返回0。如何更新分数?
import UIKit
import GoogleMobileAds
class RewardedAdViewController: UIViewController,
GADRewardBasedVideoAdDelegate {
@IBOutlet weak var scoreText: UILabel!
var score = 0
override func viewDidLoad() {
super.viewDidLoad()
GADRewardBasedVideoAd.sharedInstance().load(GADRequest(), withAdUnitID: "ca-app-pub-3940256099942544/1712485313")
GADRewardBasedVideoAd.sharedInstance().delegate = self
//let defaults = UserDefaults.standard
//defaults.set(0, forKey: "score")
}
@IBAction func playVideo(_ sender: Any) {
if GADRewardBasedVideoAd.sharedInstance().isReady == true{
GADRewardBasedVideoAd.sharedInstance().present(fromRootViewController: self )
}
}
func rewardBasedVideoAdDidClose(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
GADRewardBasedVideoAd.sharedInstance().load(GADRequest(), withAdUnitID: "ca-app-pub-3940256099942544/1712485313")
GADRewardBasedVideoAd.sharedInstance().delegate = self
}
func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd, didRewardUserWith reward: GADAdReward) {
score = score + 1
scoreText.text = String(score)
}
在上面的代码中,我首先声明了var Score = 0
,然后在代码中,当用户看完广告后,分数就会增加 1
func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd, didRewardUserWith reward: GADAdReward) {
score = score + 1
scoreText.text = String(score)
}
感谢您的帮助。
最佳答案
您可能希望使用 NSUserDefaults 将分数本地存储在 iPhone 上,从而允许关闭应用程序并将值保留在系统上 - Apple Developer Documentation
关于swift - View 更改或应用程序关闭后数字不断重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59443580/