I am trying to mock an SKProduct so I'm able to view it in the preview canvas in SwiftUI.
I have been able to create a dummy SKProduct with a convenience init inside SKProduct...
//Mock Product
convenience init(identifier: String, price: String, priceLocale: Locale) {
self.init()
self.setValue(identifier, forKey: "productIdentifier")
self.setValue(NSDecimalNumber(string: price), forKey: "price")
self.setValue(priceLocale, forKey: "priceLocale")
}
But I can't figure out how to mock introductoryPrice data. I need the subscriptionPeriod numberOfUnits and subscriptionPeriod unit
I'm not sure what keys to write to.
Any thoughts?
They are open classes so the solution is just to use inheritance, like in below demo.
So you can construct and set up your MockSK*
entities as you with and pass everywhere, where real SK*
instances expected.
import StoreKit
class MockSKProductSubscriptionPeriod: SKProductSubscriptionPeriod {
private let _numberOfUnits: Int
private let _unit: SKProduct.PeriodUnit
init(numberOfUnits: Int = 1, unit: SKProduct.PeriodUnit = .year) {
_numberOfUnits = numberOfUnits
_unit = unit
}
override var numberOfUnits: Int {
self._numberOfUnits
}
override var unit: SKProduct.PeriodUnit {
self._unit
}
}
class MockSKProduct: SKProduct {
private var _subscriptionPeriod: SKProductSubscriptionPeriod
init(subscriptionPeriod: SKProductSubscriptionPeriod = MockSKProductSubscriptionPeriod()) {
_subscriptionPeriod = subscriptionPeriod
}
override var subscriptionPeriod: SKProductSubscriptionPeriod? {
get {
_subscriptionPeriod
}
}
}