Creating protocol-driven abstractions with StoreKit 2 in Swift allows you to decouple your payment processing logic from the specific implementation of StoreKit. This can lead to more maintainable and testable code. Below, we present an example of how to achieve this using Swift protocols.
// Define a protocol for in-app purchase handling
protocol InAppPurchaseHandler {
func fetchProducts() async throws -> [Product]
func purchase(product: Product) async throws -> Transaction
func restorePurchases() async throws -> [Transaction]
}
// Implement the protocol using StoreKit 2
final class StoreKitPurchaseHandler: InAppPurchaseHandler {
func fetchProducts() async throws -> [Product] {
let products = try await Product.products(for: ["com.example.app.product1", "com.example.app.product2"])
return products
}
func purchase(product: Product) async throws -> Transaction {
let result = try await product.purchase()
switch result {
case .success(let verificationResult):
return try verificationResult.reconstructedTransaction()
case .userCancelled, .pending:
throw NSError(domain: "PurchaseError", code: 1, userInfo: [NSLocalizedDescriptionKey: "Purchase was cancelled or is pending."])
}
}
func restorePurchases() async throws -> [Transaction] {
let result = try await AppStore.sync()
return result.transactions
}
}
// Example usage
func purchaseExample() async {
let purchaseHandler: InAppPurchaseHandler = StoreKitPurchaseHandler()
do {
let products = try await purchaseHandler.fetchProducts()
if let product = products.first {
let transaction = try await purchaseHandler.purchase(product: product)
print("Purchase successful: \(transaction.id)")
}
} catch {
print("Failed to purchase: \(error.localizedDescription)")
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?