Skip to content

Commit 9559099

Browse files
committed
chore: update example.
1 parent 625c00e commit 9559099

File tree

4 files changed

+50
-37
lines changed

4 files changed

+50
-37
lines changed

!examples/InAppPurchaseManager/InAppPurchaseManager/ContentView.swift

+10-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import SwiftUI
99

1010
struct ContentView: View {
11-
@EnvironmentObject private var entitlement: EntitlementManager
11+
@EnvironmentObject private var entitlement: SubscriptionsManager
1212
@State var showingSubscriptionView = false
1313
var body: some View {
1414
VStack {
@@ -19,6 +19,15 @@ struct ContentView: View {
1919
} else {
2020
Text("You have subscribed to purchase")
2121
}
22+
23+
#if DEBUG
24+
let label = "清除 hasPro=\(entitlement.hasPro)"
25+
if entitlement.hasPro == true {
26+
Button(label) {
27+
entitlement.hasPro = false
28+
}
29+
}
30+
#endif
2231
}
2332
.padding()
2433
.sheet(isPresented: $showingSubscriptionView) {

!examples/InAppPurchaseManager/InAppPurchaseManager/InAppPurchaseManagerApp.swift

+1-9
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,10 @@ import SwiftUI
99

1010
@main
1111
struct InAppPurchaseManagerApp: App {
12-
@StateObject private var entitlementManager: EntitlementManager
13-
@StateObject private var subscriptionsManager: SubscriptionsManager
14-
init() {
15-
let entitlement = EntitlementManager()
16-
let subscriptions = SubscriptionsManager(entitlementManager: entitlement)
17-
self._entitlementManager = StateObject(wrappedValue: entitlement)
18-
self._subscriptionsManager = StateObject(wrappedValue: subscriptions)
19-
}
12+
@StateObject private var subscriptionsManager: SubscriptionsManager = SubscriptionsManager()
2013
var body: some Scene {
2114
WindowGroup {
2215
ContentView()
23-
.environmentObject(entitlementManager)
2416
.environmentObject(subscriptionsManager)
2517
}
2618
}

!examples/InAppPurchaseManager/InAppPurchaseManager/store.swift

+39-27
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,6 @@
88
import SwiftUI
99
import StoreKit
1010

11-
/// 管理用户的权限状态
12-
class EntitlementManager: ObservableObject {
13-
/// UserDefaults 实例,用于存储权限状态
14-
static let userDefaults = UserDefaults(suiteName: "com.wangchujiang.InAppPurchaseManager.vip")!
15-
/// 使用 @AppStorage 将 hasPro 属性保存到 UserDefaults 中
16-
@AppStorage("hasPro", store: userDefaults) var hasPro: Bool = false
17-
}
18-
1911
/// 管理订阅产品和购买记录
2012
@MainActor class SubscriptionsManager: NSObject, ObservableObject {
2113
/// 订阅产品的标识符数组
@@ -26,15 +18,16 @@ class EntitlementManager: ObservableObject {
2618
]
2719
/// 记录已购买的产品标识符集合
2820
var purchasedProductIDs: Set<String> = []
21+
/// UserDefaults 实例,用于存储权限状态
22+
static let userDefaults = UserDefaults(suiteName: "com.wangchujiang.InAppPurchaseManager.vip")!
23+
/// 使用 @AppStorage 将 hasPro 属性保存到 UserDefaults 中
24+
@AppStorage("hasPro", store: userDefaults) var hasPro: Bool = false
2925
/// 发布订阅产品信息
3026
@Published var products: [Product] = []
31-
/// 授权管理器
32-
private var entitlementManager: EntitlementManager? = nil
3327
/// 更新任务
3428
private var updates: Task<Void, Never>? = nil
3529
/// 初始化方法,接收 EntitlementManager 实例作为参数
36-
init(entitlementManager: EntitlementManager) {
37-
self.entitlementManager = entitlementManager
30+
override init() {
3831
super.init()
3932
// 监听交易更新
4033
self.updates = observeTransactionUpdates()
@@ -115,21 +108,40 @@ extension SubscriptionsManager {
115108
func updatePurchasedProducts() async {
116109
/// 一系列最新交易,使用户有权进行应用内购买和订阅。
117110
for await result in Transaction.currentEntitlements {
118-
guard case .verified(let transaction) = result else {
119-
continue
120-
}
121-
if transaction.revocationDate == nil {
122-
// 如果交易未被撤销,则将产品标识符添加到已购买集合中
123-
if !self.purchasedProductIDs.contains(transaction.productID) {
124-
self.purchasedProductIDs.insert(transaction.productID)
125-
}
126-
} else {
127-
// 如果交易被撤销,则从已购买集合中移除产品标识符
128-
self.purchasedProductIDs.remove(transaction.productID)
111+
guard case .verified(let transaction) = result else { continue }
112+
handleTransaction(transaction)
113+
}
114+
}
115+
// MARK: - 处理交易
116+
/// 处理交易
117+
private func handleTransaction(_ transaction: StoreKit.Transaction) {
118+
if transaction.revocationDate == nil {
119+
// 如果交易未被撤销,则将产品标识符添加到已购买集合中
120+
if !self.purchasedProductIDs.contains(transaction.productID) {
121+
self.purchasedProductIDs.insert(transaction.productID)
129122
}
123+
} else {
124+
// 如果交易被撤销,则从已购买集合中移除产品标识符
125+
self.purchasedProductIDs.remove(transaction.productID)
130126
}
131-
// 更新 EntitlementManager 的 hasPro 属性
132-
self.entitlementManager?.hasPro = !self.purchasedProductIDs.isEmpty
127+
128+
// 通过 productID 获取 Product 对象
129+
guard let product = products.first(where: { $0.id == transaction.productID }) else {
130+
// 处理 product 不存在的情况
131+
print("Product with ID \(transaction.productID) not found.")
132+
return
133+
}
134+
135+
if let expirationDate = transaction.expirationDate, product.type == .autoRenewable {
136+
// 更新 EntitlementManager 的 hasPro 属性
137+
hasPro = !isExpirationDate(expirationDate: expirationDate)
138+
}
139+
}
140+
141+
// MARK: - 判断订阅是否过期
142+
/// 判断订阅是否过期
143+
func isExpirationDate(expirationDate: Date) -> Bool {
144+
return expirationDate > Date() // 如果 expirationDate 在 currentDate 之后,返回 true 表示未过期
133145
}
134146
// MARK: - 恢复购买
135147
/// 异步恢复购买
@@ -140,13 +152,13 @@ extension SubscriptionsManager {
140152
// 更新已购买的产品
141153
await updatePurchasedProducts()
142154
} catch {
143-
print(error)
155+
print("Restore purchases failed: \(error.localizedDescription)")
144156
}
145157
}
146158
}
147159

148160
// MARK: - SKPaymentTransactionObserver 实现
149-
extension SubscriptionsManager: SKPaymentTransactionObserver {
161+
extension SubscriptionsManager: @preconcurrency SKPaymentTransactionObserver {
150162
// 支付队列更新交易
151163
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
152164
print("Subscriptions Payment Queue! updated!")

0 commit comments

Comments
 (0)