swiftxcodeadmobnsuserdefaultsadmob-rewardedvideoad

Rewarded Video ad show reward content on my label


I just working on an app with admob rewarded video ad. I wanna know when the user click button to reward them. I made this but my question is when I click second time on play ad button my current (Currency on label) not plusing with new one it just get new 100 not (current + 100). I just wanna to make my (Current) currency (+100). can you guys help meee. please....

struct Keys {
    static var currency = "Currency"
    static var currentCurr = "CurrentCurrency"
}

class ViewController: UIViewController, GADRewardBasedVideoAdDelegate {

    var currency = 0
    var userDefault = UserDefaults.standard

    @IBOutlet weak var currencyShower: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()

        GADRewardBasedVideoAd.sharedInstance().load(GADRequest(), withAdUnitID: "ca-app-pub-3940256099942544/1712485313")
        GADRewardBasedVideoAd.sharedInstance().delegate = self

        if userDefault.string(forKey: Keys.currency) != nil {
            currencyShower.text = userDefault.string(forKey: Keys.currency)
        } else {
            return
        }
    }
    //
    @IBOutlet weak var playAdOut: UIButton!
    @IBAction func playAd(_ sender: UIButton) {
        if GADRewardBasedVideoAd.sharedInstance().isReady == true {
            GADRewardBasedVideoAd.sharedInstance().present(fromRootViewController: self)
        } else {
            print("Video Did not Load...")
        }
    }

    func rewardBasedVideoAdDidClose(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
        print("Video is Ready")
        GADRewardBasedVideoAd.sharedInstance().load(GADRequest(),
                                                    withAdUnitID: "ca-app-pub-3940256099942544/1712485313")
    }
    func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd, didFailToLoadWithError error: Error) {
        print("Error When Loading")
    }
    func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd, didRewardUserWith reward: GADAdReward) {
        currency += 100
        currencyShower.text = String(currency)
    }
}

Solution

  • You could save currency value to UserDefaults and then retrieve or update it when needed example in following link: example

    PS! If you don't want to save strings to userDefaults you can also save numbers.