Sources/OrgApp/TipStore.swift
60 lines · 2196 bytes
3 symbols in this file
1#if canImport(StoreKit)
2import Foundation
3import Observation
4import StoreKit
5
6/// Tips from the App Store. `ProStore`'s transaction listener finishes any that arrive later.
7@MainActor @Observable
8public final class TipStore {
9 public private(set) var products: [Product] = []
10 public private(set) var isLoading = false
11 public private(set) var purchasingProductID: String?
12 /// A failure, or a tip waiting for approval, shown in the section.
13 public private(set) var message: String?
14 /// Set after a tip goes through; the thank-you alert clears it.
15 public var thanked = false
16
17 public init() {}
18
19 public func loadProducts() async {
20 guard !isLoading else { return }
21 isLoading = true
22 message = nil
23 defer { isLoading = false }
24 do {
25 let fetched = try await Product.products(for: Tip.productIDs)
26 products = Tip.productIDs.compactMap { id in fetched.first { $0.id == id } }
27 if products.count < Tip.productIDs.count {
28 message = String(localized: "Some tips aren't available from the App Store right now.")
29 }
30 } catch {
31 products = []
32 message = String(localized: "The App Store can't be reached right now.")
33 }
34 }
35
36 public func purchase(_ product: Product) async {
37 guard purchasingProductID == nil else { return }
38 purchasingProductID = product.id
39 message = nil
40 defer { purchasingProductID = nil }
41 do {
42 switch try await product.purchase() {
43 case .success(.verified(let transaction)):
44 await transaction.finish()
45 thanked = true
46 case .success(.unverified):
47 message = String(localized: "The App Store couldn't verify the purchase.")
48 case .pending:
49 message = String(localized: "The tip is waiting for approval.")
50 case .userCancelled:
51 break
52 @unknown default:
53 break
54 }
55 } catch {
56 message = String(localized: "The purchase didn't go through. \(error.localizedDescription)")
57 }
58 }
59}
60#endif