iOS 14 应用内购买请求登录/验证两次

Blu*_*Med 3 in-app-purchase ios swift ios14

我正在向应用程序添加一个非消耗性功能。一切正常,除了购买操作请求登录,成功后几乎立即紧跟另一个登录表。如果第二次登录成功,则订单进入完成,否则失败。诊断打印跟踪(下方)显示 UpdateTransactions Observer 将“处理中”事件视为队列中的单个事件,然后是两个登录表,然后是“已购买”事件。调用时观察者队列中只有一个项目,这一切似乎都发生在 Apple 内部,过程结束。恢复功能正常工作。此行为发生在我的设备本地以及我的 TestFlight beta 人员身上。有谁知道发生了什么?

Buy button tapped
Entered delegate Updated transactions with n = 1 items
   TransactionState = 0
Updated Tranaction: purch in process

    At this point, the signin sheet appears, pw entered, then a ping and DONE is checked
    
    a few seconds later, the signin re-appears, pw again re-entered and again success signaled on sheet

Entered delegate Updated transactions with n = 1 items
   TransactionState = 1
Update Transaction : Successful Purchase
Run Code Online (Sandbox Code Playgroud)

下面是我相当普通的 IAP 管理器类的代码:

class IAPManager: NSObject {
    
// MARK: - Properties
    static let shared = IAPManager()
        
// MARK: - Init
    private override init() {
        super.init()
    }
       
//MARK: - Control methods
    func startObserving() {
        SKPaymentQueue.default().add(self)
    }

    func stopObserving() {
        SKPaymentQueue.default().remove(self)
    }
    
    
    func canMakePayments() -> Bool {
        return SKPaymentQueue.canMakePayments()
    }
    
    func peelError(err: SKError) -> String {
        let userInfo = err.errorUserInfo
        let usr0 = userInfo["NSUnderlyingError"] as! NSError
        let usr1 = (usr0.userInfo["NSUnderlyingError"] as! NSError).userInfo
        let usr2 = usr1["NSLocalizedDescription"] as? String
        return usr2 ?? "\nreason not available"
    }
    
    
//MARK: - Generic Alert for nonVC instances
    func simpleAlert(title:String, message:String) -> Void {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let ok = UIAlertAction(title: "OK", style: .default, handler: nil)
        alert.addAction(ok)
        if #available(iOS 13.0, *) {
            var topWindow = UIApplication.shared.currentWindow
            if topWindow == nil {
                topWindow = UIApplication.shared.currentWindowInactive
            }
            let topvc = topWindow?.rootViewController?.presentedViewController
            topvc?.present(alert, animated: false, completion: nil)
            if var topController = UIApplication.shared.keyWindow?.rootViewController  {
                   while let presentedViewController = topController.presentedViewController {
                         topController = presentedViewController
                   }
 //          topController.present(alert, animated: false, completion: nil)
             }
        } else {
            var alertWindow : UIWindow!
            alertWindow = UIWindow.init(frame: UIScreen.main.bounds)
            alertWindow.rootViewController = UIViewController.init()
            alertWindow.windowLevel = UIWindow.Level.alert + 1
            alertWindow.makeKeyAndVisible()
            alertWindow.rootViewController?.present(alert, animated: false)
        }
    }

    
// MARK: - Purchase Products
    
    func buy(product:String) -> Bool {
        if !canMakePayments() {return false}
        let paymentRequest = SKMutablePayment()
        paymentRequest.productIdentifier = product
        SKPaymentQueue.default().add(paymentRequest)
        return true
    }
    
    func restore() -> Void {
        SKPaymentQueue.default().restoreCompletedTransactions()
    }

}

// MARK: -  Methods Specific to my app
func enableBigD() -> Void {
    let glob = Globals.shared
    let user = UserDefaults.standard
.........
        //Post local notification signal that purch success/restored (to change UI in BuyView)
        NotificationCenter.default.post(name: Notification.Name(rawValue: NotificationNames.kNotificationBuyDictEvent), object: nil)
        

}


// MARK: - SKPaymentTransactionObserver
extension IAPManager: SKPaymentTransactionObserver {
    
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        //Debugging Code
        print("Entered delegate Updated transactions with n = \(transactions.count) items")
        for tx in transactions {
            print("   TransactionState = \(tx.transactionState.rawValue)")
        }
        // END debugging code

        transactions.forEach { (transaction) in
            switch transaction.transactionState {
            case .purchased:
                enableBigD()
                print("Update Transaction : Successful Purchase")
                SKPaymentQueue.default().finishTransaction(transaction)
                simpleAlert(title: "Purchase Confirmed", message: "Thank You!")

            case .restored:
                print("Update Transaction : Restored Purchase")
                enableBigDict()
                SKPaymentQueue.default().finishTransaction(transaction)
                simpleAlert(title: "Success", message: "Your access has been restored!")

            case .failed:
                print("Updated Tranaction: FAIL")
                if let err = transaction.error as? SKError {
                    let reason = peelError(err: err)
                    simpleAlert(title: "Purchase Problem", message: "Sorry, the requested purchase did not complete.\nThe reason was: \n\(err.localizedDescription) because:\(reason)")
                }
                UserDefaults.standard.set(false, forKey: Keys.kHasPaidForDict)
                SKPaymentQueue.default().finishTransaction(transaction)
                
            case .deferred:
                print("Updated Transaction: purch deferred ")
                if let err = transaction.error as? SKError {
                    print("purch deferred \(err.localizedDescription)")
                }
                break

            case .purchasing:
                print("Updated Tranaction: purch in process ")
                break
            @unknown default:
                print("Update Transaction: UNKNOWN STATE!")
                break
            }
        }
    }
    
    func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
        let err = error.localizedDescription
        let reason = peelError(err: error as! SKError)
        let fullerr = "The Restore request had a problem. If it persists after retrying, Please send us a note with the Code through the Feedback button in Settings.  The Error Code is: \(err) because \(reason)"
        simpleAlert(title: "Restore Problem", message: fullerr)
    }
        
    
}   //end Extension of Queue Observer



//MARK: - Extension on UIAppl to get current Window in Scene-based iOS14 environment
//      /sf/ask/3990649841/

extension UIApplication {
    var currentWindow: UIWindow? {
        connectedScenes
            .filter(({$0.activationState == .foregroundActive}))
        .map({$0 as? UIWindowScene})
        .compactMap({$0})
        .first?.windows
        .filter({$0.isKeyWindow}).first
    }
    
    var currentWindowInactive: UIWindow? {
        connectedScenes
            .filter(({$0.activationState == .foregroundInactive}))
        .map({$0 as? UIWindowScene})
        .compactMap({$0})
        .first?.windows
        .filter({$0.isKeyWindow}).first
    }
}
Run Code Online (Sandbox Code Playgroud)

mat*_*att 5

是的,我刚刚写了一篇关于这个的文章。(尚未发布。)基本上这是整个应用程序内购买用于测试的方式中的一个错误。您只需要忽略对话循环出现两次的事实。

如果您完全退出您的paymentQueue(_:updatedTransactions:)实现(您已经这样做了,除非您应该使用 OSLog 而不是print),您会发现那里的一切都在正确发生。它对对话的双循环一无所知,这一切都完全不发生在进程之外。

只有当您是 TestFlight 测试员或使用沙箱测试员帐户时才会出现此问题。

因此,自本次发行并不会影响代码的工作,并且因为它不会当一个真正的用户做这一点,你只需要闭上眼睛,继续工作。不要担心,并警告您的 TestFlight 用户并告诉他们不要担心。