Skip to content

Commit

Permalink
Improved checking for products in SKHelperStoreView
Browse files Browse the repository at this point in the history
  • Loading branch information
russell-archer committed Oct 14, 2024
1 parent 4e30ac3 commit b762f8f
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions Sources/SKHelper/Views/SKHelperStoreView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import SwiftUI
import StoreKit
import Combine

/// Uses the StoreKit `StoreView` to create a list of all avaliable products.
@available(iOS 17.0, macOS 14.6, *)
Expand All @@ -27,6 +28,9 @@ public struct SKHelperStoreView<Content: View>: View {
/// True if the store has products.
@State private var hasProducts = false

/// Used to cancel the refresh products task.
@State private var refreshProductsTask: (any Cancellable)?

/// A closure which is called to display product details.
private var productDetails: ProductDetailsClosure?

Expand All @@ -35,7 +39,10 @@ public struct SKHelperStoreView<Content: View>: View {

/// Provides a collection of `Product` to display in the StoreView.
private var products: [Product] { productIds == nil ? store.allProducts : store.products(from: productIds!) }


/// Used to check mutliple times for product availability.
private let refreshProducts = Timer.publish(every: 1, on: .main, in: .common)

/// Creates an `SKHelperStoreView` showing all available products. When you instantiate this view provide a closure that may be
/// called to display product information. This information will be displayed when the user taps on the product's image.
///
Expand Down Expand Up @@ -77,7 +84,7 @@ public struct SKHelperStoreView<Content: View>: View {
public init(productIds: [ProductId]) where Content == EmptyView {
self.productIds = productIds
}

/// Creates an `SKHelperStoreView` showing all available products.
/// Default product information will be displayed when the user taps on the product's image.
///
Expand Down Expand Up @@ -110,7 +117,7 @@ public struct SKHelperStoreView<Content: View>: View {
if let productDetails { SKHelperProductView(selectedProductId: $selectedProductId, showProductInfoSheet: $productSelected, productDetails: productDetails) }
else { SKHelperProductView(selectedProductId: $selectedProductId, showProductInfoSheet: $productSelected) }
}
.onChange(of: store.products) { hasProducts = store.hasProducts }

} else {

VStack {
Expand All @@ -119,6 +126,11 @@ public struct SKHelperStoreView<Content: View>: View {
ProgressView()
}
.padding()
.task { refreshProductsTask = refreshProducts.connect() }
.onReceive(refreshProducts, perform: { _ in
hasProducts = store.hasProducts
if hasProducts, let refreshProductsTask { refreshProductsTask.cancel() }
})
}
}
}
Expand Down

0 comments on commit b762f8f

Please sign in to comment.