Reputation: 123
My restore purchases seems to work correctly, except it crashes the app when you press it a second time. Is there a work around for this? Here is my code:
import UIKit
import StoreKit
class SettingsVC: UIViewController, SKPaymentTransactionObserver {
@IBOutlet weak var restorePurchaseButton: UIButton!
@IBOutlet weak var privacyPolicyButton: UIButton!
@IBOutlet weak var termsofUseButton: UIButton!
@IBOutlet weak var unlockButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
SKPaymentQueue.default().add(self)
checkUnlockButton()
}
@IBAction func RestoreBtnClicked(_ sender: Any) {
SKPaymentQueue.default().restoreCompletedTransactions()
restorePurchaseButton.isEnabled = false
}
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction in transactions{
if transaction.transactionState == .restored{
UserDefaults.standard.set(true, forKey: "payment")
SKPaymentQueue.default().finishTransaction(transaction)
}
}
}
Edit: Here is the second view controller. It contains the button that allows the user to purchase the product. The restore purchase button is in a separate view controller. I am relatively new to Swift so please try to dumb down your answer for me haha.
import Foundation
import UIKit
import StoreKit
class UnlockContentVC: UIViewController, SKPaymentTransactionObserver {
@IBOutlet weak var removeAds: UIButton!
@IBOutlet weak var noThanks: UIButton!
override func viewDidLoad() {
//removeAds.layer.cornerRadius = 10
SKPaymentQueue.default().add(self)
removeAds.layer.cornerRadius = removeAds.frame.height / 2
}
@IBAction func dismissModal(_ sender: Any) {
navigationController?.popViewController(animated: true)
dismiss(animated: true, completion: nil)
}
@IBAction func OnClickUlockBtn(_ sender: Any) {
if SKPaymentQueue.canMakePayments(){
//can make payments
let paymentRequest = SKMutablePayment()
paymentRequest.productIdentifier = productID
SKPaymentQueue.default().add(paymentRequest)
}else{
//can't make payments
print("Device can not make payments...")
}
}
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction in transactions{
if transaction.transactionState == SKPaymentTransactionState.purchased{
//User Payment Successfull
UserDefaults.standard.set(true, forKey: "payment")
print("payment was successfull")
SKPaymentQueue.default().finishTransaction(transaction)
}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: 82
Reputation: 123
Fixed.
override func viewDidDisappear(_ animated: Bool) {
SKPaymentQueue.default().remove(self)
}
Upvotes: 1