Douglas W. Palme
Douglas W. Palme

Reputation: 571

Breaking out of a For statement and still allowing a completion handler to complete successfully

I have a RevenueCat implementation that is working but I don't like the flow and am struggling with improving it. I know there has to be a more refined way to do this, so any help would be appreciated:

@IBAction func btnMnthlyPressed(_ sender: Any) {
    Purchases.shared.offerings { (offerings, error) in
        if let e = error {
            print(e.localizedDescription)
        }
        
        guard let offering = offerings?.current else {
            print("No current offering configured")
            return
        }
        
        for package in offering.availablePackages {
            print(package.identifier)
            if package.identifier == "$rc_monthly" {
                Purchases.shared.purchasePackage(package) { (transaction, info, error, cancelled) in
                    if cancelled {
                        print("User cancelled purchase")
                        return
                    }
                    // Optionally handle specific purchase errors
                     if info?.entitlements.all["FullAccess"]?.isActive == true {
                        print("Unlocked Pro Cats 🎉")
                    }
                }
            }
            print("Product: \(package.product.localizedDescription), price: \(package.localizedPriceString)")
        }
    }
}

Maybe I'm trying to do too much in the func...

Upvotes: 0

Views: 92

Answers (1)

enc_life
enc_life

Reputation: 5169

Taking the first monthly package is probably better than a for loop since you don't want to ever initiate two purchase calls on the same button press.

@IBAction func btnMnthlyPressed(_ sender: Any) {
    Purchases.shared.offerings { (offerings, error) in
        if let e = error {
            print(e.localizedDescription)
        }
        
        guard let offering = offerings?.current else {
            print("No current offering configured")
            return
        }
        
        guard let package = offering.availablePackages.first(where: { $0.packageType == .monthly }) else {
            print("No monthly package type")
            return
        }
        
        Purchases.shared.purchasePackage(package) { (transaction, info, error, cancelled) in
            if cancelled {
                print("User cancelled purchase")
                return
            }
            // Optionally handle specific purchase errors
             if info?.entitlements.all["FullAccess"]?.isActive == true {
                print("Unlocked Pro Cats 🎉")
            }
        }
    }
}

That said, you may want to get all the packages when the view is loaded to make sure they exist before the user tries to tap the buy button.

Upvotes: 1

Related Questions