krz/hutch
an ios client for sourcehut
clone: git clone https://gitbay.org/krz/hutch.git
v3.1.7: Hutch/Views/More/TipStoreViewModel.swift · raw
1import StoreKit
2
3@Observable
4final class TipStoreViewModel {
5 var products: [Product] = []
6 var isLoading = false
7 var errorMessage: String?
8
9 private let productIDs = [
10 "net.cleberg.hutch.tip.small",
11 "net.cleberg.hutch.tip.medium",
12 "net.cleberg.hutch.tip.large"
13 ]
14
15 func loadProducts() async {
16 isLoading = true
17 defer { isLoading = false }
18 do {
19 let fetched = try await Product.products(for: productIDs)
20 // Sort by price ascending to maintain small/medium/large order
21 products = fetched.sorted { $0.price < $1.price }
22 } catch {
23 errorMessage = error.localizedDescription
24 }
25 }
26
27 func purchase(_ product: Product) async {
28 do {
29 let result = try await product.purchase()
30 switch result {
31 case .success(let verification):
32 if case .verified(let transaction) = verification {
33 await transaction.finish()
34 }
35 case .userCancelled, .pending:
36 break
37 @unknown default:
38 break
39 }
40 } catch {
41 errorMessage = error.localizedDescription
42 }
43 }
44}