第2次按下“恢复购买”按钮会使应用崩溃,

时间:2019-02-06 21:05:49

标签: ios swift xcode store

我的还原购买似乎可以正常工作,除了再次按下该应用会使应用崩溃。有没有解决的办法?这是我的代码:

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)

       }
    }
}

编辑:这是第二个视图控制器。它包含允许用户购买产品的按钮。恢复购买按钮在单独的视图控制器中。我对Swift来说还比较陌生,所以请尝试为我简化答案。

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)")
            }
        } 
    }
}

}

1 个答案:

答案 0 :(得分:1)

固定。

override func viewDidDisappear(_ animated: Bool) {
   SKPaymentQueue.default().remove(self)
}