"SwiftyStoreKit.completeTransactions() should only be called once when the app launches."

"SwiftyStoreKit.completeTransactions() should only be called once when the app launches."

我将 SwiftyStoreKit 与 SwiftUI 和 App 一起使用,而不是 App Delegate,并在控制台中收到此消息:“SwiftyStoreKit.completeTransactions() 只应在应用程序启动时调用一次。”我相信这是因为我在下面的块中调用了 completeTransactions,我可以从 Print 语句中看到它比以前调用 AppDelegate 的 didFinishLaunching 更频繁地被调用。我关注此消息的原因是我在尝试购买时因崩溃而被 App Review 拒绝。我还应该在哪里调用 completeTransactions?

     .onChange(of: scenePhase) { newScenePhase in
                switch newScenePhase {
                case .active:
                    print("App is active")

  SwiftyStoreKit.completeTransactions(atomically: true) { purchases in
            
            for purchase in purchases {
                switch purchase.transaction.transactionState {
                case .purchased, .restored:
                    let downloads = purchase.transaction.downloads
                    if !downloads.isEmpty {
                        SwiftyStoreKit.start(downloads)
                    } else if purchase.needsFinishTransaction {
                        // Deliver content from server, then:
                        SwiftyStoreKit.finishTransaction(purchase.transaction)
                    }
                    print("\(purchase.transaction.transactionState.debugDescription): \(purchase.productId)")
                case .failed, .purchasing, .deferred:
                    break // do nothing
                @unknown default:
                    break // do nothing
                }
            }
        }
                    

尝试在应用程序主初始化中执行此操作,例如

@main
struct MyApp: App {

    init() {
        SwiftyStoreKit.completeTransactions(atomically: true) { purchases in
           // ... other code here
        }
    }

    var body: some Scene {
        WindowGroup {
           ContentView()
        }
    }
}

注意:如果时间太早,您可以定义应用程序委托适配器(如此处)并在完成启动回调时调用SwiftyStoreKit .