A modern, SwiftUI-friendly StoreKit 2 wrapper for iOS and macOS in-app purchases. SwiftStore handles transaction verification, entitlement management, and state updates for subscription and lifetime (non-consumable) products β with an observable event stream, standalone test instances, and type-safe product identifiers.
Consumable products are not managed by this library.
- π Easy Setup: Closure-based configuration, safe to use with strict concurrency checking
- π± SwiftUI Integration: Built-in
@SwiftStoreStateproperty wrapper - π Single Transaction Pipeline: Platform transactions verified, completed, and fanned out to every store instance exactly once per process
- π° Product Types: Subscription and lifetime (non-consumable) products
- π‘οΈ Transaction Verification: Unverified transactions are ignored β never trusted, never acknowledged
- π©Ή Grace Period Aware: Subscriptions in the platform's billing grace period / retry keep access
- π‘ Observable Events:
onEventreports entitlement changes, purchases, verification failures, and restores - π§ͺ Standalone Instances:
make()/init()for tests, previews, and isolated environments - β‘ Observable State: Uses Swift's Observation framework for reactive SwiftUI updates
- iOS 17+ / macOS 14+
- Swift 6.2 toolchain (Xcode 26+)
- In Xcode, go to File β Add Package Dependenciesβ¦
- Enter the repository URL:
https://github.com/NguyenPhongVN/swift-store - Select a version (dependency rule: Up to Next Major from 1.0.0) and add the SwiftStore product to your target
Or in your Package.swift:
dependencies: [
.package(url: "https://github.com/NguyenPhongVN/swift-store", from: "1.0.0")
]Initialize in your app's entry point. The closure runs on the main actor, so this is safe with strict concurrency checking:
import SwiftUI
import SwiftStore
@main
struct MyApp: App {
init() {
SwiftStore.shared.initialize {
$0.setSubscriptionIDs(["monthly_premium", "yearly_premium"])
$0.setLifetimeIDs(["lifetime_premium"])
$0.setTermsURL("https://yourapp.com/terms")
$0.setPrivacyURL("https://yourapp.com/privacy")
}
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}If you prefer an explicit configuration object, the classic variant works the same way:
let configuration = SSConfiguration()
configuration.subscriptionIDs = ["monthly_premium"]
configuration.lifetimeIDs = ["lifetime_premium"]
SwiftStore.shared.initialize(configuration: configuration)Use the @SwiftStoreState property wrapper for reactive state:
import SwiftUI
import SwiftStore
struct ContentView: View {
@SwiftStoreState private var store
var body: some View {
VStack(spacing: 20) {
if store.isPremium {
Text("π Premium Active!")
if let subscription = store.activeSubscription {
Text("Active Subscription: \(subscription)")
}
if store.activeLifeTime {
Text("Lifetime Premium Active")
}
} else {
Text("Upgrade to Premium")
}
}
.padding()
}
}Purchases happen through the platform's StoreKit views, which report purchase progress (including Ask to Buy .pending) through their own callbacks:
import SwiftUI
import StoreKit
struct Paywall: View {
var body: some View {
SubscriptionStoreView(groupID: "YOUR_SUBSCRIPTION_GROUP_ID") {
Text("Unlock Premium")
}
}
}Once a purchase is approved, SwiftStore processes the transaction automatically and premium state updates.
Subscribe to the event stream for analytics, logging, or UI hints:
SwiftStore.shared.onEvent = { event in
switch event {
case .entitlementChanged(let productID, let isActive):
print("Entitlement \(productID) is now \(isActive ? "active" : "inactive")")
case .purchaseFinished(let productID):
print("Purchase completed: \(productID)")
case .transactionUnverified:
print("A transaction failed verification and was ignored")
case .restoreFinished:
print("Restore finished")
}
}Events are delivered on the main actor in occurrence order. Unverified transactions change no state; unrecognized verified products are completed but grant nothing.
// Distinguishable outcome; throws on failure (for example, offline).
let outcome = try await SwiftStore.shared.restore()
switch outcome {
case .restored(let count):
print("Restored β \(count) active entitlements")
case .nothingToRestore:
print("Nothing to restore")
}
// Legacy variant: reports via the .restoreFinished event only, never throws.
await SwiftStore.shared.restorePurchases()Most apps use shared. For tests, previews, or isolated environments, create independent instances β each keeps its own configuration, state, and event slot, while platform monitoring still runs once per process:
let store = SwiftStore.make()
print(store.isInitialized) // false β safe defaults until initialized
store.initialize {
$0.setLifetimeProductIDs([ProductID("lifetime_premium")])
}- Single pipeline: monitoring runs once per process; outcomes are applied once per initialized instance.
- Product-scoped clearing: one product's expiry or revocation never clears another product's entitlement.
- Grace retention: a subscription inside the platform's billing grace period (or billing retry) keeps access; access is removed only on true lapse.
- Hygiene: verified transactions are completed exactly once; unverified ones are ignored and never finished.
- Type safety:
ProductIDandclassify(_:)avoid raw-string mistakes;termsLink/privacyLinkgive validatedURL?accessors (no force-unwrapping).
public final class SwiftStore {
public static let shared: SwiftStore
public static func make() -> SwiftStore
public var activeLifeTime: Bool // managed by the store β writing deprecated
public var activeSubscription: String? // managed by the store β writing deprecated
public var isPremium: Bool { get }
public var termsURL: String?
public var privacyURL: String?
public var termsLink: URL? // validated (nil when unset/malformed)
public var privacyLink: URL?
public var productIDs: [String]
public var onEvent: ((StoreEvent) -> Void)?
public var isInitialized: Bool
public func initialize(_ configure: (SSConfiguration) -> Void) -> SwiftStore
public func initialize(configuration: SSConfiguration) -> SwiftStore
public func hasEntitlement(_ id: ProductID) -> Bool
public func restore() async throws -> RestoreOutcome
public func restorePurchases() async
public func showManageSubscriptions(in scene: UIWindowScene) // iOS only
}public class SSConfiguration { // typealias StoreConfiguration
public init()
public var subscriptionIDs: [String]
public var lifetimeIDs: [String]
public var termsURL: String?
public var privacyURL: String?
public func setSubscriptionIDs(_ ids: [String]) -> Self
public func setLifetimeIDs(_ ids: [String]) -> Self
public func setSubscriptionProductIDs(_ ids: [ProductID]) -> Self
public func setLifetimeProductIDs(_ ids: [ProductID]) -> Self
public func setTermsURL(_ url: String?) -> Self
public func setPrivacyURL(_ url: String?) -> Self
public func classify(_ id: String) -> ProductClassification
public func classify(_ id: ProductID) -> ProductClassification
}public enum StoreEvent: Sendable, Equatable {
case entitlementChanged(productID: String, isActive: Bool)
case purchaseFinished(productID: String)
case transactionUnverified
case restoreFinished
}
public struct ProductID: Hashable, Sendable, ExpressibleByStringLiteral {
public let rawValue: String
}
public enum RestoreOutcome: Sendable, Equatable {
case restored(count: Int)
case nothingToRestore
}
public enum ProductClassification: Sendable, Equatable {
case lifetime, subscription, unrecognized
}
public enum ProductType { // legacy β kept for compatibility
case lifetime, subscription
@available(*, deprecated, message: "Use ProductClassification.unrecognized instead.")
case none
}@propertyWrapper
public struct SwiftStoreState: DynamicProperty {
public init(_ viewModel: SwiftStore = .shared)
public var wrappedValue: SwiftStore // read store state
public var projectedValue: Binding<SwiftStore>
}
β οΈ Deprecated: assigning entitlement state through@SwiftStoreStatedynamic member lookup (for examplestore.activeLifeTime = true) is deprecated β entitlement state is managed by the store and treated as read-only. Writable access will be removed in a future major version.
- Full release history: CHANGELOG.md
- In-code documentation: β₯-click any symbol in Xcode for Quick Help
This project is licensed under the MIT License β see LICENSE for details.