Force a Save on a Document Based iOS App in SwiftUI

Currently, I am developing a small document based App for iOS with SwiftUI. I was quite surprised to see that there is no obvious way to save the document’s contents to file after editing. In fact, the default behaviour was that nothing was saved at all after editing my document’s content. On macOS there is at least the possibility to update the change count to force a save later but that is not available on iOS SwiftUI.

Well, there is this hint on stackoverflow to register an undo at the UndoManager even if you do not use it. For some Views that worked for me; for others it didn’t. I was getting tired to spend hours in investigating why this was so. So I was looking for a way to save the document’s content explicitly. This is what I came up with.

Weiterlesen

Open the last used document on App startup

Did you ever want your app to open the last used document on startup? Well, that’s not too difficult on macOS. In your NSDocumentController subclass you have the array of recentDocumentURLs, and on startup you can try to open the first member if it exists.

But on iOS it’s a little bit more tricky. There is no such array as on macOS. So we have to mimic it by ourself.

This is a review of my post 2 years ago: UIDocumentBrowserViewController and External Storage

Weiterlesen

Creating a macOS document based app with SwiftUI and the new App protocol

Have you already tried to create a macOS document based app with SwiftUI and the new App protocol? Well, there are some problems to solve esp. if you want to use menus focused on the currently open document.

In the old app cycle with AppDelegate / SceneDelegate you still had to use the storyboard to define the menu items and link them to your methods in your document class derived from NSDocument. Enabling and disabling of the menu item according to the open documents was automatically managed by the frameworks.

That’s not the case in the new App protocol of SwiftUI anymore. Instead, you can define your menus and menu items quite nicely in your App struct conforming to the new App protocol but there is no automatic link to the current document in focus.

Weiterlesen