summaryrefslogtreecommitdiff
path: root/Hutch/Views/More/TipStoreViewModel.swift
blob: 54868bab02bc7a0cbe335b9443230da16c24f639 (plain) (blame)
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
import StoreKit

@Observable
final class TipStoreViewModel {
    var products: [Product] = []
    var isLoading = false
    var errorMessage: String?

    private let productIDs = [
        "net.cleberg.hutch.tip.small",
        "net.cleberg.hutch.tip.medium",
        "net.cleberg.hutch.tip.large"
    ]

    func loadProducts() async {
        isLoading = true
        defer { isLoading = false }
        do {
            let fetched = try await Product.products(for: productIDs)
            // Sort by price ascending to maintain small/medium/large order
            products = fetched.sorted { $0.price < $1.price }
        } catch {
            errorMessage = error.localizedDescription
        }
    }

    func purchase(_ product: Product) async {
        do {
            let result = try await product.purchase()
            switch result {
            case .success(let verification):
                if case .verified(let transaction) = verification {
                    await transaction.finish()
                }
            case .userCancelled, .pending:
                break
            @unknown default:
                break
            }
        } catch {
            errorMessage = error.localizedDescription
        }
    }
}