Search code examples
iosswiftin-app-purchase

Swift: Make SKPayment with only the product Id


I'm trying to instantiate an SKPayment object

let payment = SKPayment(product: product)

All I know is the productID

var productID = "MyId"

Apples documentation mentions some delegate methods for accessing the product, productsRequest(_ request: SKProductsRequest, didReceive response: SKProd but the problem is that their delegate methods, so I can't call them and don't know how to use them to get my products


If you want to view the bigger project instead of just whats on this question, the project is on this github


Solution

  • If all you have is the productID then you must make a request to app store connect in order to obtain the product objects.

    let productIdentifiers: Set<ProductIdentifier> = ["myId"]
    let store = IAPHelper(productIds: productIdentifiers)
    var products = [SKProduct]
    
    store.requestProducts{ [weak self] success, products in
            guard let self = self 
            else { return }
            if success {
                self.products = products!
            }
        }
    }
    

    Once you have the products you can loop through them and see if any of their identifiers match the productID of interest. If one does, you can use that product.

    for prod in self.products{
        if prod.productIdentifier == "myId"{
            let payment = SKPayment(product: product)
            SKPaymentQueue.default().add(payment)
        }
    }