|
| 1 | +import Foundation |
| 2 | +@_exported import StoreKit |
| 3 | + |
| 4 | +@globalActor public actor StoreActor { |
| 5 | + |
| 6 | + static let subscriptionIDs: Set<String> = { |
| 7 | + guard let storefrontPreferences = Bundle.main.object(forInfoDictionaryKey: "Storefront") as? [String: Any], let subscriptions = storefrontPreferences["Subscriptions"] as? [String] else { |
| 8 | + print("No Subscriptions in Storefront plist key") |
| 9 | + return [] |
| 10 | + } |
| 11 | + |
| 12 | + print(subscriptions) |
| 13 | + return Set(subscriptions) |
| 14 | + }() |
| 15 | + |
| 16 | + static let purchaseIDs: Set<String> = { |
| 17 | + guard let storefrontPreferences = Bundle.main.object(forInfoDictionaryKey: "Storefront") as? [String: Any], let purchases = storefrontPreferences["Purchases"] as? [String] else { |
| 18 | + print("No Purchases in Storefront plist key") |
| 19 | + return [] |
| 20 | + } |
| 21 | + |
| 22 | + precondition(!purchases.isEmpty, "Purchases must contain exactly one element") |
| 23 | + |
| 24 | + print(purchases) |
| 25 | + return Set(purchases) |
| 26 | + }() |
| 27 | + |
| 28 | + static let allProductIDs: Set<String> = { |
| 29 | + subscriptionIDs.union(purchaseIDs) |
| 30 | + }() |
| 31 | + |
| 32 | + public static let shared = StoreActor() |
| 33 | + |
| 34 | + private var loadedProducts: [String: Product] = [:] |
| 35 | + private var lastLoadError: Error? |
| 36 | + private var productLoadingTask: Task<Void, Never>? |
| 37 | + |
| 38 | + private var transactionUpdatesTask: Task<Void, Never>? |
| 39 | + private var statusUpdatesTask: Task<Void, Never>? |
| 40 | + private var storefrontUpdatesTask: Task<Void, Never>? |
| 41 | + |
| 42 | + public nonisolated let productController: StoreProductController |
| 43 | + public nonisolated let subscriptionController: StoreSubscriptionController |
| 44 | + |
| 45 | + init() { |
| 46 | + self.productController = StoreProductController(identifiedBy: Self.purchaseIDs) |
| 47 | + self.subscriptionController = StoreSubscriptionController(productIDs: Array(Self.subscriptionIDs)) |
| 48 | + Task(priority: .background) { |
| 49 | + await self.setupListenerTasksIfNecessary() |
| 50 | + await self.loadProducts() |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + public func product(identifiedBy productID: String) async -> Product? { |
| 55 | + await waitUntilProductsLoaded() |
| 56 | + return loadedProducts[productID] |
| 57 | + } |
| 58 | + |
| 59 | + private func setupListenerTasksIfNecessary() { |
| 60 | + if transactionUpdatesTask == nil { |
| 61 | + transactionUpdatesTask = Task(priority: .background) { |
| 62 | + for await update in StoreKit.Transaction.updates { |
| 63 | + await self.handle(transaction: update) |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + if statusUpdatesTask == nil { |
| 68 | + statusUpdatesTask = Task(priority: .background) { |
| 69 | + for await update in Product.SubscriptionInfo.Status.updates { |
| 70 | + await subscriptionController.handle(update: update) |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + if storefrontUpdatesTask == nil { |
| 75 | + storefrontUpdatesTask = Task(priority: .background) { |
| 76 | + for await update in Storefront.updates { |
| 77 | + self.handle(storefrontUpdate: update) |
| 78 | + } |
| 79 | + } |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + private func waitUntilProductsLoaded() async { |
| 84 | + if let task = productLoadingTask { |
| 85 | + await task.value |
| 86 | + } |
| 87 | + // You load all the products at once, so you can skip this if the |
| 88 | + // dictionary is empty. |
| 89 | + else if loadedProducts.isEmpty { |
| 90 | + let newTask = Task { |
| 91 | + await loadProducts() |
| 92 | + } |
| 93 | + productLoadingTask = newTask |
| 94 | + await newTask.value |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + private func loadProducts() async { |
| 99 | + do { |
| 100 | + let products = try await Product.products(for: Self.allProductIDs) |
| 101 | + try Task.checkCancellation() |
| 102 | + print("Loaded \(products.count) products") |
| 103 | + loadedProducts = products.reduce(into: [:]) { |
| 104 | + $0[$1.id] = $1 |
| 105 | + } |
| 106 | + let premiumProduct: Product? = Self.purchaseIDs.first.flatMap { loadedProducts[$0] } |
| 107 | + Task(priority: .utility) { @MainActor in |
| 108 | + self.productController.product = premiumProduct |
| 109 | + self.subscriptionController.subscriptions = products |
| 110 | + .compactMap { Subscription(subscription: $0) } |
| 111 | + // Now that you have loaded the products, have the subscription |
| 112 | + // controller update the entitlement based on the group ID. |
| 113 | + await self.subscriptionController.updateEntitlement() |
| 114 | + } |
| 115 | + } catch { |
| 116 | + print("Failed to get in-app products: \(error)") |
| 117 | + lastLoadError = error |
| 118 | + } |
| 119 | + productLoadingTask = nil |
| 120 | + } |
| 121 | + |
| 122 | + private func handle(transaction: VerificationResult<StoreKit.Transaction>) async { |
| 123 | + guard case .verified(let transaction) = transaction else { |
| 124 | + print("Received unverified transaction: \(transaction)") |
| 125 | + return |
| 126 | + } |
| 127 | + // If you have a subscription, call checkEntitlement() which gets the |
| 128 | + // full status instead. |
| 129 | + if transaction.productType == .autoRenewable { |
| 130 | + await subscriptionController.updateEntitlement() |
| 131 | + } else if transaction.productID == Self.purchaseIDs.first { |
| 132 | + await productController.set(isEntitled: !transaction.isRevoked) |
| 133 | + } |
| 134 | + await transaction.finish() |
| 135 | + } |
| 136 | + |
| 137 | + private func handle(storefrontUpdate newStorefront: Storefront) { |
| 138 | + print("Storefront changed to \(newStorefront)") |
| 139 | + // Cancel existing loading task if necessary. |
| 140 | + if let task = productLoadingTask { |
| 141 | + task.cancel() |
| 142 | + } |
| 143 | + // Load products again. |
| 144 | + productLoadingTask = Task(priority: .utility) { |
| 145 | + await self.loadProducts() |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | +} |
| 150 | + |
| 151 | +public extension StoreKit.Transaction { |
| 152 | + var isRevoked: Bool { |
| 153 | + // The revocation date is never in the future. |
| 154 | + revocationDate != nil |
| 155 | + } |
| 156 | +} |
0 commit comments