I am currently having an issue getting the correct activation state on app launch to show the SK Store Review Controller. So I call it in onAppear:
import SwiftUI
@main
struct UltimatePortfolio3App: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
@StateObject var dataController: DataController
@StateObject var unlockManager: UnlockManager
init() {
let dataController = DataController()
let unlockManager = UnlockManager(dataController: dataController)
_dataController = StateObject(wrappedValue: dataController)
_unlockManager = StateObject(wrappedValue: unlockManager)
}
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, dataController.container.viewContext)
.environmentObject(dataController)
.environmentObject(unlockManager)
.onReceive(
// Automatically save when we detect that we are no longer
// the foreground app. User this rather than the scene phase
// API so we can port to macOS, where scene phase won't detect
// our app losing focus as of macOS 11.1.
NotificationCenter.default.publisher(
for: UIApplication.willResignActiveNotification
),
perform: save
)
.onAppear(perform: dataController.appLaunched)
}
}
func save(_ note: Notification) {
dataController.save()
}
}
Then in the appLaunched method:
import Foundation
import StoreKit
extension DataController {
func appLaunched() {
guard count(for: Project.fetchRequest()) >= 5 else { return }
let allScenes = UIApplication.shared.connectedScenes
let scene = allScenes.first { $0.activationState == .foregroundActive }
if let windowScene = scene as? UIWindowScene {
SKStoreReviewController.requestReview(in: windowScene)
}
}
}
The issue is that the only scene I get back in the Set of connectedScenes has an activationState of UISceneActivationStateForegroundInactive
, meaning the scene constant and windowScene are therefore nil, meaning there is no windowScene to pass into the requestReview. I am running iOS 15.4 and my target deployment is iOS 15.2 in Xcode 13.3.
(lldb) po allScenes.first
▿ Optional<UIScene>
- some : <UIWindowScene: 0x13f1046e0; scene = <FBSScene: 0x2802b2f00; identifier: sceneID:com.davidhughes.UltimatePortfolio6-CF060879-F738-43EC-A7D2-01BF4C7D769C>; persistentIdentifier = CF060879-F738-43EC-A7D2-01BF4C7D769C; activationState = UISceneActivationStateForegroundInactive; settingsScene = <UIWindowScene: 0x13f1046e0>; windows = (
"<UIWindow: 0x13dd11270; frame = (0 0; 428 926); gestureRecognizers = <NSArray: 0x2822ebc30>; layer = <UIWindowLayer: 0x2822eb9c0>>"
)>