UIWindowScene and State Restoration
UIWindowScene and State Restoration for iOS
Why is userActivity
or stateRestorationActivity
property nil
after I restart my app?
For state restoration of a scene session, you need to assign a NSUserActivity
to the correct UIWindowScene
property with your view controller's viewWillAppear
method, then in the viewWillDisappear
assign nil
to that property.
Make sure to assign it to the UIViewController
that is the rootViewController
for the UIWindow
being shown. Meaning, if you have a UINavigationController
as the parent, use navigationController?.view.window?.windowScene?.userActivity
.
A code example is available, not mine, but a helpful one.
It seems like the state restoration subsystem takes the user activity from any view controllers of active scenes and stores the state from it, which makes sense.
Other notes:
- Make sure to store your information in
NSUserActivity.userInfo
. - For macOS apps, make sure you don’t restart the app too quickly, since apps may linger in the background before their process is terminated. Use the
Activity Monitor
to make sure the process is terminated before you restart.