Restore State from NSUserActivity

I just discovered the composable architecture and are evaluating it for a project. I'm very thankful for the excellent documentation and example projects in the repo. However there is (so far) one piece missing for me:
What's the best/right way to encode/decode a TCA store/state to NSUserActivity in the scene delegate?

1 Like

This sounds a bit to easy to be true, but couldn’t you “just” extract the values from your UserActivity and set them as part of your Stores initialState? You get the NSUserActivity in willConnectToSession via the session. That’s where I typically set up the Store anyways.

1 Like

Yes, that what I do now, but..

I'm tempted to have a store property in the scene delegate and use some kind of "restore:from" action to send but I haven't quite figured out how to interact with the store directly.

And I'm still not able to get the state from the store (it's internal) for encoding. I guess the way to go is something similar to the "WithViewStore" to get a LocalState but I haven't figured out how.

1 Like

Ah, I see. For encoding so far I assigned e.g. in a ViewController (I’m still using UIKit) an NSUserActivity to the windowScene and returned that in the SceneDelegates restorationActivity method. Maybe instead you can observe the state via a ViewStore inside your SceneDelegate, map it to a corresponding NSUserActivity, and assign it to the windowScene. So e.g. scope your state to selectedDocumentURL, create a ViewStore for that and assign it to your windowScene.userActivity.

use some kind of "restore:from"

If you want to send an action (e.g. restoreFromActivity(_:NSUserActivity)) to your store after initializing the store you’d have to go through the ViewStore.

ViewStore(store).send(.restoreFromActivity(activity))

Thanks! The ViewStore initialiser worked for me. Feels a little strange to use it outside a view thou..
I can use the ViewStore object to send the restore action and to dump the state property into the NSUserActivity.

1 Like

Maybe it feels a bit less strange if you think of the ViewStore as a View into your Store instead of a thing related to UI.

4 Likes

How about treating the method that needs to encode the NSUserActivity as a dependency in the environment?. Then a reducer just needs to run a Effect that calls that method when needed.