// // TransactionObserver.swift // PDFReaderPro // // Created by zenghong on 1/8/25. // import Foundation import SwiftUI import StoreKit @available(macOS 12.0, *) @objc final class TransactionObserver: NSObject { var updates: Task? = nil // @Environment(\.displayStoreKitMessage) private var displayStoreMessage static let shared = TransactionObserver() override init() { super.init() updates = newTransactionListenerTask() } deinit { // Cancel the update handling task when you deinitialize the class. updates?.cancel() } private func newTransactionListenerTask() -> Task { Task(priority: .background) { for await verificationResult in Transaction.updates { self.handle(updatedTransaction: verificationResult) } // for await message in StoreKit.Message.messages { // if message.reason != .winBackOffer { // Ask the system to display messages now. // try? await displayStoreMessage(message) // } // } } } private func handle(updatedTransaction verificationResult: VerificationResult) { guard case .verified(let transaction) = verificationResult else { // Ignore unverified transactions. return } print("同步购买信息:\(transaction)") if let revocationDate = transaction.revocationDate { // Remove access to the product identified by transaction.productID. // Transaction.revocationReason provides details about // the revoked transaction. } else if let expirationDate = transaction.expirationDate, expirationDate < Date() { // Do nothing, this subscription is expired. print("订阅过期") return } else if transaction.isUpgraded { // Do nothing, there is an active transaction // for a higher level of service. return } else { // Provide access to the product identified by // transaction.productID. } } }