I am making an app in SwiftUI using an In-app purchase. In this app, the user should be able to buy points as many times as he wants, so I have used consumable products (in the app store connect). But when I've tried to buy them once again I got the information "This In-App purchase has already been bought. It will be restored for free". I've already searched for a way how to do it but none of the ideas worked for me. Here is my StoreManager class:
import Foundation
import StoreKit
import SwiftUI
class StoreManager : NSObject, ObservableObject, SKProductsRequestDelegate {
@EnvironmentObject var authViewModel: AuthViewModel
@Published var transactionState: SKPaymentTransactionState?
@Published var myProducts = [SKProduct]()
var request: SKProductsRequest!
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
print("Did receive response")
if !response.products.isEmpty {
for fetchedProduct in response.products {
DispatchQueue.main.async {
self.myProducts.append(fetchedProduct)
}
}
for invalidIdentifier in response.invalidProductIdentifiers {
print("Invalid identifiers found: \(invalidIdentifier)")
}
}else{
print("it's empty")
}
}
func getProducts(productIDs: [String]) {
let request = SKProductsRequest(productIdentifiers: Set(productIDs))
request.delegate = self
request.start()
}
func request(_ request: SKRequest, didFailWithError error: Error) {
print("Request did fail: \(error)")
}
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction in transactions {
switch transaction.transactionState {
case .purchasing:
transactionState = .purchasing
break
case .purchased:
print("purchased")
queue.finishTransaction(transaction)
transactionState = .purchased
break
case .restored:
print("restored")
transactionState = .restored
queue.finishTransaction(transaction)
break
case .failed, .deferred:
queue.finishTransaction(transaction)
transactionState = .failed
break
default:
queue.finishTransaction(transaction)
break
}
}
}
func purchaseProduct(product: SKProduct) {
if SKPaymentQueue.canMakePayments() {
let payment = SKPayment(product: product)
SKPaymentQueue.default().add(payment)
} else {
print("User can't make payment.")
}
}
func restoreProducts() {
SKPaymentQueue.default().restoreCompletedTransactions()
}
}
And I am simply using getProducts with onAppear, and purchase product on button's action. Please help me or if an answer to a similar question already exists send me a link to that thread.