TransactionObserver.swift 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. //
  2. // TransactionObserver.swift
  3. // PDFReaderPro
  4. //
  5. // Created by zenghong on 1/8/25.
  6. //
  7. import Foundation
  8. import SwiftUI
  9. import StoreKit
  10. @available(macOS 12.0, *)
  11. @objc final class TransactionObserver: NSObject {
  12. var updates: Task<Void, Never>? = nil
  13. // @Environment(\.displayStoreKitMessage) private var displayStoreMessage
  14. static let shared = TransactionObserver()
  15. override init() {
  16. super.init()
  17. updates = newTransactionListenerTask()
  18. }
  19. deinit {
  20. // Cancel the update handling task when you deinitialize the class.
  21. updates?.cancel()
  22. }
  23. private func newTransactionListenerTask() -> Task<Void, Never> {
  24. Task(priority: .background) {
  25. for await verificationResult in Transaction.updates {
  26. self.handle(updatedTransaction: verificationResult)
  27. }
  28. // for await message in StoreKit.Message.messages {
  29. // if message.reason != .winBackOffer {
  30. // Ask the system to display messages now.
  31. // try? await displayStoreMessage(message)
  32. // }
  33. // }
  34. }
  35. }
  36. private func handle(updatedTransaction verificationResult: VerificationResult<StoreKit.Transaction>) {
  37. guard case .verified(let transaction) = verificationResult else {
  38. // Ignore unverified transactions.
  39. return
  40. }
  41. print("同步购买信息:\(transaction)")
  42. if let revocationDate = transaction.revocationDate {
  43. // Remove access to the product identified by transaction.productID.
  44. // Transaction.revocationReason provides details about
  45. // the revoked transaction.
  46. } else if let expirationDate = transaction.expirationDate,
  47. expirationDate < Date() {
  48. // Do nothing, this subscription is expired.
  49. print("订阅过期")
  50. return
  51. } else if transaction.isUpgraded {
  52. // Do nothing, there is an active transaction
  53. // for a higher level of service.
  54. return
  55. } else {
  56. // Provide access to the product identified by
  57. // transaction.productID.
  58. }
  59. }
  60. }