This commit is contained in:
Trey t
2022-07-18 20:14:48 -05:00
parent 044e0bb027
commit 53334e5fb8
10 changed files with 134 additions and 10 deletions

View File

@@ -20,7 +20,8 @@ public enum StoreError: Error {
class IAPManager: ObservableObject {
@Published private(set) var showIAP = false
@Published private(set) var subscriptions = [Product: (status: [Product.SubscriptionInfo.Status], renewalInfo: RenewalInfo)?]()
@AppStorage(UserDefaultsStore.Keys.firstLaunchDate.rawValue, store: GroupUserDefaults.groupDefaults) private var firstLaunchDate = Date()
public var sortedSubscriptionKeysByPriceOptions: [Product] {
subscriptions.keys.sorted(by: {
$0.price < $1.price
@@ -74,23 +75,52 @@ class IAPManager: ObservableObject {
var updateListenerTask: Task<Void, Error>? = nil
public var daysLeftBeforeIAP: Int {
let daysSinceInstall = Calendar.current.dateComponents([.day, .hour, .minute, .second], from: firstLaunchDate, to: Date())
if let days = daysSinceInstall.day {
return 30 - days
}
return 0
}
public var expireDate: Date? {
Calendar.current.date(byAdding: .day, value: 30, to: firstLaunchDate) ?? nil
}
private let iapIdentifiers = Set([
"com.88oakapps.ifeel.IAP.subscription.weekly",
"com.88oakapps.ifeel.IAP.subscription.monthly",
"com.88oakapps.ifeel.IAP.subscription.yearly"
])
var expireOnTimer: Timer?
init() {
//Start a transaction listener as close to app launch as possible so you don't miss any transactions.
updateListenerTask = listenForTransactions()
refresh()
setUpdateTimer()
}
deinit {
updateListenerTask?.cancel()
}
func setUpdateTimer() {
if let expireDate = expireDate {
expireOnTimer = Timer.init(fire: expireDate, interval: 0, repeats: false, block: { _ in
self.decideShowIAP()
})
RunLoop.main.add(expireOnTimer!, forMode: .common)
} else {
if let expireOnTimer = expireOnTimer {
expireOnTimer.invalidate()
}
}
}
func refresh() {
Task {
//During store initialization, request products from the App Store.
@@ -104,16 +134,25 @@ class IAPManager: ObservableObject {
}
func decideShowIAP() {
guard !subscriptions.isEmpty else {
return
}
var tmpShowIAP = true
// if we have a sub in the subscriptions dict
// then we dont need to show
for (_, value) in self.subscriptions {
if value != nil {
tmpShowIAP = false
DispatchQueue.main.async {
self.showIAP = false
}
return
}
}
var tmpShowIAP = true
// if its passed 30 days with no sub
if daysLeftBeforeIAP <= 0 {
tmpShowIAP = true
} else {
tmpShowIAP = false
}
DispatchQueue.main.async {
self.showIAP = tmpShowIAP
}