I want to load the SKProducts before the actual page is shown. But I have some difficulties with creating it.
What I thought was to made another class that loads the products, like this:
class GetIapInfo: NSObject, SKProductsRequestDelegate {
var list = [SKProduct]()
var p = SKProduct()
let audio = "com.xxx";
let video = "com.xxx"
let complete = "com.xxx"
override init() {
super.init()
if SKPaymentQueue.canMakePayments() {
print("starting IAPS")
let productIdentifiers = Set([audio, vídeo, complete])
let request = SKProductsRequest(productIdentifiers: productIdentifiers)
request.delegate = self
request.start()
} else {
print("please enable IAPS")
}
}
internal func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
print("product request")
let myProduct = response.products
for product in myProduct {
print("product added from ding")
print(product.productIdentifier)
print(product.localizedTitle)
print(product.localizedDescription)
print(product.price)
}
}
}
But this only calls the init method and that's it, it doesn't call the productsRequest method. Has that something to do with the delegate?
And how am I going to save the products that are going to return in that method? Because I need them later.
You probably should keep around a reference to the SKProductsRequest object you created inside your GetIapInfo.init(). Your current code will deallocate the request object the moment the init method exists. This might explain why your delegate isn't being called at all ;)
From the SKProductsRequest class documentation:
Be sure to keep a strong reference to the request object; otherwise, the system might deallocate the request before it can complete.
For instance, create a stored property for it:
private let request: SKProductsRequest!
Might also be a good idea to track any request related errors by implementing this delegate method as well:
func request(_ request: SKRequest, didFailWithError error: Error) {
print("Request failed: \(error)")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With