Search code examples
swiftswiftuistorekitreview

Asking the user to review the app after a certain number of launches


I'd like to ask the user to review the app after a certain number of launches. But for a reason I don't understand, the "StoreKit review pop-up" isn't shown. The if let scene = code is however correct because in a button it works well.

import SwiftUI
import StoreKit

@main
struct ExampleApp: App {
    @AppStorage("launchNumber") var launchNumber: Int = 0

    var body: some Scene {
        WindowGroup {
            ContentView()
                .onAppear { review() }
        }
    }

    func review() {
        launchNumber += 1
        // print(launchNumber)
        guard launchNumber == 2 else { return }
        if let scene = UIApplication.shared.connectedScenes.first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene {
            SKStoreReviewController.requestReview(in: scene)
        }
    }
}

Do you know why it's not shown when launchNumber == 2?


Solution

  • Use .task instead, onAppear is known for having issues presenting other Views without a delay.

    var body: some Scene {
        WindowGroup {
            ContentView()
                .task { review() }
        }
    }
    

    If you absolutely have to use onAppear you can set a delay.

    var body: some Scene {
        WindowGroup {
            ContentView()
                .onAppear { 
                     DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                        review() 
                     }
                 }
        }
    }