This repository was archived by the owner on Oct 16, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathSubscriptionFlowScreen.swift
More file actions
331 lines (296 loc) · 12.7 KB
/
SubscriptionFlowScreen.swift
File metadata and controls
331 lines (296 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import SwiftUI
import OpenIAP
@available(iOS 15.0, *)
struct SubscriptionFlowScreen: View {
@StateObject private var iapStore = OpenIapStore()
// UI State
@State private var showError = false
@State private var errorMessage = ""
// Product IDs for subscription testing
private let subscriptionIds: [String] = [
"dev.hyo.martie.premium"
]
var body: some View {
ScrollView(.vertical, showsIndicators: true) {
VStack(spacing: 20) {
VStack(alignment: .leading, spacing: 16) {
HStack {
Image(systemName: "repeat.circle.fill")
.font(.largeTitle)
.foregroundColor(AppColors.secondary)
VStack(alignment: .leading, spacing: 4) {
Text("Subscription Management")
.font(.headline)
Text("iOS")
.font(.caption)
.padding(.horizontal, 8)
.padding(.vertical, 2)
.background(AppColors.secondary.opacity(0.2))
.cornerRadius(4)
}
Spacer()
}
Text("Manage your premium subscriptions and auto-renewable purchases.")
.font(.subheadline)
.foregroundColor(.secondary)
}
.padding()
.background(AppColors.cardBackground)
.cornerRadius(12)
.shadow(radius: 2)
.padding(.horizontal)
if iapStore.status.isLoading {
LoadingCard(text: "Loading subscriptions...")
} else {
let subscriptionProducts = iapStore.products.filter { $0.typeIOS.isSubs }
if subscriptionProducts.isEmpty {
EmptyStateCard(
icon: "repeat.circle",
title: "No subscriptions available",
subtitle: "Configure subscription products in App Store Connect"
)
} else {
ForEach(subscriptionProducts, id: \.id) { product in
SubscriptionCard(
product: product,
purchase: iapStore.availablePurchases.first { $0.productId == product.id },
isSubscribed: {
if let purchase = iapStore.availablePurchases.first(where: { $0.productId == product.id }) {
if let expirationTime = purchase.expirationDateIOS {
let expirationDate = Date(timeIntervalSince1970: expirationTime / 1000)
return expirationDate > Date.now
} else {
return purchase.isAutoRenewing
}
}
return false
}(),
isCancelled: {
if let purchase = iapStore.availablePurchases.first(where: { $0.productId == product.id }) {
let isActive: Bool
if let expirationTime = purchase.expirationDateIOS {
let expirationDate = Date(timeIntervalSince1970: expirationTime / 1000)
isActive = expirationDate > Date.now
} else {
isActive = purchase.isAutoRenewing
}
return purchase.isAutoRenewing == false && isActive
}
return false
}(),
isLoading: iapStore.status.isPurchasing(product.id),
onSubscribe: {
let isSubscribed = {
if let purchase = iapStore.availablePurchases.first(where: { $0.productId == product.id }) {
if let expirationTime = purchase.expirationDateIOS {
let expirationDate = Date(timeIntervalSince1970: expirationTime / 1000)
return expirationDate > Date.now
} else {
return purchase.isAutoRenewing
}
}
return false
}()
if isSubscribed {
Task {
await manageSubscriptions()
}
} else {
purchaseProduct(product)
}
},
onManage: {
Task {
await manageSubscriptions()
}
}
)
}
}
}
VStack(alignment: .leading, spacing: 12) {
Text("Notes")
.font(.headline)
VStack(alignment: .leading, spacing: 8) {
Text("• Subscriptions may take a moment to reflect")
Text("• Use Sandbox account for testing")
Text("• Restore purchases to sync status")
}
.font(.caption)
}
.padding()
.background(AppColors.secondary.opacity(0.05))
.overlay(
RoundedRectangle(cornerRadius: 8)
.stroke(AppColors.secondary.opacity(0.3), lineWidth: 1)
)
.cornerRadius(8)
.padding(.horizontal)
Button(action: {
Task {
await restorePurchases()
}
}) {
HStack {
Image(systemName: "arrow.clockwise.circle")
Text("Restore Purchases")
Spacer()
Image(systemName: "arrow.up.forward.app")
}
.padding()
.background(AppColors.secondary)
.foregroundColor(.white)
.cornerRadius(8)
}
.padding(.horizontal)
Spacer(minLength: 20)
}
.padding(.vertical)
}
.background(AppColors.background)
.navigationTitle("Subscriptions")
.navigationBarTitleDisplayMode(.large)
.navigationBarItems(trailing:
Button {
loadProducts()
} label: {
Image(systemName: "arrow.clockwise")
}
.disabled(iapStore.status.isLoading)
)
.alert("Error", isPresented: $showError) {
Button("OK") {}
} message: {
Text(errorMessage)
}
.onAppear {
setupIapProvider()
}
.onDisappear {
teardownConnection()
}
}
// MARK: - OpenIapStore Setup
private func setupIapProvider() {
print("🔷 [SubscriptionFlow] Setting up OpenIapStore...")
// Setup callbacks
iapStore.onPurchaseSuccess = { purchase in
Task { @MainActor in
self.handlePurchaseSuccess(purchase)
}
}
iapStore.onPurchaseError = { error in
Task { @MainActor in
self.handlePurchaseError(error)
}
}
Task {
do {
try await iapStore.initConnection()
print("✅ [SubscriptionFlow] Connection initialized")
loadProducts()
await loadPurchases()
} catch {
await MainActor.run {
errorMessage = "Failed to initialize connection: \(error.localizedDescription)"
showError = true
}
}
}
}
private func teardownConnection() {
print("🔷 [SubscriptionFlow] Tearing down connection...")
Task {
try await iapStore.endConnection()
print("✅ [SubscriptionFlow] Connection ended")
}
}
// MARK: - Product and Purchase Loading
private func loadProducts() {
Task {
await MainActor.run {
// Loading state is managed internally
}
defer {
Task { @MainActor in
// Loading state is managed internally
}
}
do {
try await iapStore.fetchProducts(skus: subscriptionIds, type: .subs)
await MainActor.run {
if iapStore.products.isEmpty {
errorMessage = "No subscription products found. Please check your App Store Connect configuration."
showError = true
}
}
} catch {
await MainActor.run {
errorMessage = "Failed to load products: \(error.localizedDescription)"
showError = true
}
}
}
}
private func loadPurchases() async {
do {
try await iapStore.getAvailablePurchases()
} catch {
await MainActor.run {
errorMessage = "Failed to load purchases: \(error.localizedDescription)"
showError = true
}
}
}
// MARK: - Purchase Flow
private func purchaseProduct(_ product: OpenIapProduct) {
print("🔄 [SubscriptionFlow] Starting subscription purchase for: \(product.id)")
Task {
do {
let params = RequestPurchaseProps(
sku: product.id,
andDangerouslyFinishTransactionAutomatically: true
)
_ = try await iapStore.requestPurchase(params)
} catch {
// Error is already handled by OpenIapStore internally
print("❌ [SubscriptionFlow] Purchase failed: \(error.localizedDescription)")
}
}
}
private func restorePurchases() async {
do {
try await iapStore.refreshPurchases(forceSync: true)
await MainActor.run {
print("✅ [SubscriptionFlow] Restored \(iapStore.availablePurchases.count) purchases")
}
} catch {
await MainActor.run {
errorMessage = "Failed to restore purchases: \(error.localizedDescription)"
showError = true
}
}
}
private func manageSubscriptions() async {
do {
_ = try await iapStore.showManageSubscriptionsIOS()
} catch {
await MainActor.run {
errorMessage = "Failed to open subscription management: \(error.localizedDescription)"
showError = true
}
}
}
// MARK: - Event Handlers
private func handlePurchaseSuccess(_ purchase: OpenIapPurchase) {
print("✅ [SubscriptionFlow] Subscription successful: \(purchase.productId)")
// Reload purchases to update UI
Task {
await loadPurchases()
}
}
private func handlePurchaseError(_ error: OpenIapError) {
print("❌ [SubscriptionFlow] Subscription error: \(error.message)")
// Error status is already handled internally by OpenIapStore
}
}