belgrim
belgrim

Reputation: 123

Is this function not recognizing my key when removing ads through in-app purchase?

The ad works fine. However, when I add the if else statement to figure out if the user paid to remove ads, the ad doesn't pop up even if they haven't paid to have ads removed. The only print statement I get is "it called something" so I feel like there is something wrong with the key "Purchased". I checked to make sure they matched. Did I do something wrong with the key?

func showAd() {

    if let purchased = UserDefaults.standard.value(forKey: "Purchased") as? Bool{
        if purchased == true{
            interstitial = nil
            print("there is no ad!!!!")
        }else{
            self.interstitial = createInterstitialAd()
            print("there is an ad!!!")
        }
    } else {
        print("it called something")
    }

}

Edit: Here is the code where I set the key.

func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
    for transaction in transactions{
        if transaction.transactionState == SKPaymentTransactionState.purchased{
            //User Payment Successfull
            UserDefaults.standard.set(true, forKey: "Purchased")
            print("payment was successfull")
            SKPaymentQueue.default().finishTransaction(transaction)
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let controller = storyboard.instantiateViewController(withIdentifier: "homeVC")
            self.navigationController?.pushViewController(controller, animated: true)

        }else if transaction.transactionState == .failed{
            //User Payment failed
            print("transaction failed...")
            SKPaymentQueue.default().finishTransaction(transaction)
            if let error = transaction.error {
                print("\(error.localizedDescription)")
            }
        } 
    }
}

Upvotes: 0

Views: 30

Answers (1)

nighttalker
nighttalker

Reputation: 946

Change this line:

if let purchased = UserDefaults.standard.value(forKey: "Purchased") as? Bool

To:

if let purchased = UserDefaults.standard.bool(forKey: "Purchased")

This makes it so purchased is not an optional. That way if purchased will always get called.

In fact, I would get rid of if let as it can't be nil:

let purchased = UserDefaults.standard.bool(forKey: "Purchased")

Upvotes: 1

Related Questions