Thanks for being a part of WWDC25!

How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here

Calling Async Functions in SwiftUI

Hi,

I'd like to call an Async function upon a state change or onAppear() but I'm not sure how to do so. Below is my code:

.onAppear() {
    if !subscribed {
         await Subscriptions().checkSubscriptionStatus()
    }
}

class Subscriptions {
    var subscribed = UserDefaults.standard.bool(forKey: "subscribed")
    
    func checkSubscriptionStatus() async {
        if !subscribed {
            await loadProducts()
        }
    }
    
    func loadProducts() async {
        for await purchaseIntent in PurchaseIntent.intents {
            // Complete the purchase workflow.
            await purchaseProduct(purchaseIntent.product)
        }
    }
    
    func purchaseProduct(_ product: Product) async {
        // Complete the purchase workflow.
        do {
            try await product.purchase()
        }
        catch {
            // Add your error handling here.
        }
        // Add your remaining purchase workflow here.
    }
}

Use the task(priority:_:) modifier. It allows you to perform an asynchronous task with a lifetime that matches that of the view.

Discover concurrency in SwiftUI dives deep into how you can use Swift's concurrency features in your SwiftUI app. It's a great resource you should review.

Calling Async Functions in SwiftUI
 
 
Q