Solved

Multiple Subscription Buttons SwiftUI

  • 23 February 2022
  • 2 replies
  • 112 views

Badge +3

Hi all! I followed this video: https://www.youtube.com/watch?v=0H2SdKf4ot0 which was immensely helpful in helping me get RC setup in my SwiftUI app. I was able to get purchasing working for a single subscription using a button:

 

                VStack {
Button(action: {
Purchases.shared.offerings { offerings, error in
if let packages = offerings?.current?.availablePackages {
Purchases.shared.purchasePackage(packages.first!, { transaction, purchaserInfo, error, userCancelled in
print("TRANSACTION: \(transaction)")
print("PURCHASER INFO: \(purchaserInfo)")
print("USER CANCELED: \(userCancelled)")

if purchaserInfo?.entitlements["Pro"]?.isActive == true {
}
})
}
}

}, label: {
Text("1 month")
.foregroundColor(.white)
.frame(maxWidth: 280)
})

}

 

The challenge I’m facing now is that I have 3 purchase options for my one Entitlement : monthly sub, annual sub, and lifetime. These are all ready configured in App Store Connect and on RC. 

Since this example uses `packages.first` (and correctly grabs the monthly sub) how do I configure my yearly and lifetime buttons? There’s no `packages.second` or `packages.third`

Appreciate any insight. Thanks!

icon

Best answer by joshdholtz 24 February 2022, 17:10

View original

2 replies

Userlevel 3
Badge +5

Hey @thatvirtualboy

Fancy meeting you here 😊 

I use a `ForEach` to iterate over `offerings?.current?.availablePackagees` from  `Purchases.shared.offerings`. Here is sample code (copied and modified) from one of my apps:

struct MyView: View {

@State private var packages = [Purchases.Package]()

var body: some View {
VStack {
ForEach(packages, id: \.self) { package in
Button {
// Purchase package
} label: {
Text(package.localizedPriceString)
}
}
}.onAppear {
Purchases.shared.offerings { (offerings, error) in
if let offering = offerings?.current {
packages = offering.availablePackages
}
}
}
}
}

Warning: This may not compile but hopefully this helps 🙂

Badge +3

Ohhhh Hey!

Thanks @joshdholtz! Indeed I’m able to use that code to iterate over the purchase options, works like a charm! The trick now is getting each button to fit my original design idea 🧐

Thanks a bunch!

Reply