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 pathTransactionObserver.swift
More file actions
93 lines (79 loc) · 2.7 KB
/
TransactionObserver.swift
File metadata and controls
93 lines (79 loc) · 2.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
import SwiftUI
import OpenIAP
@MainActor
@available(iOS 15.0, *)
class TransactionObserver: ObservableObject {
@Published var latestPurchase: IapPurchase?
@Published var errorMessage: String?
@Published var isPending = false
private let iapModule = IapModule.shared
init() {
setupListeners()
}
deinit {
// Clean up listeners
iapModule.removeAllPurchaseUpdatedListeners()
iapModule.removeAllPurchaseErrorListeners()
}
private func setupListeners() {
// Add purchase updated listener
iapModule.addPurchaseUpdatedListener { [weak self] purchase in
Task { @MainActor in
self?.handlePurchaseUpdated(purchase)
}
}
// Add purchase error listener
iapModule.addPurchaseErrorListener { [weak self] error in
Task { @MainActor in
self?.handlePurchaseError(error)
}
}
}
private func handlePurchaseUpdated(_ purchase: IapPurchase) {
print("✅ Purchase successful: \(purchase.productId)")
latestPurchase = purchase
isPending = false
errorMessage = nil
}
private func handlePurchaseError(_ error: IapError) {
print("❌ Purchase failed: \(error)")
errorMessage = error.localizedDescription
isPending = false
}
}
// Example usage in SwiftUI View
struct TransactionObserverExampleView: View {
@StateObject private var observer = TransactionObserver()
var body: some View {
VStack(spacing: 20) {
Text("Transaction Observer Example")
.font(.title)
if observer.isPending {
ProgressView("Transaction pending...")
}
if let purchase = observer.latestPurchase {
VStack(alignment: .leading) {
Text("Latest Purchase:")
.font(.headline)
Text("Product: \(purchase.productId)")
Text("Date: \(Date(timeIntervalSince1970: purchase.purchaseTime / 1000), formatter: dateFormatter)")
}
.padding()
.background(Color.green.opacity(0.1))
.cornerRadius(8)
}
if let error = observer.errorMessage {
Text("Error: \(error)")
.foregroundColor(.red)
.padding()
}
}
.padding()
}
private var dateFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
return formatter
}
}