swiftuitextviewuipasteboardenvironmentobject

Recommended Way to Temporarily Store Text and Cursor Position for UITextView When Backgrounded


I have a UITextView with an attributedString for the text. When I either close and re-open the view or background the app and come back, the text in the textView disappears. I want to be able to temporarily save it until the user submits it. What is the recommended way?

I tried UIPasteboard first, but have ran into weird issues with my textview acting funky after the app is backgrounded and I come back. The text is there, but the cursor position is never updated and updateUIView in UIViewRepresentable is never called anymore.

I could also create an environment object to store the text and cursor position until the user is ready to submit.

Any insight onto the proper strategy?


Solution

  • I recommend using userdefaults to save short temporary data. When the user backgrounds the application you can set a notification to go off and your viewcontroller can observe for the notification. You can also use the same notification to fetch the text data from userdefaults and show it on textView