BLACK FRIDAY SALE: Save big on all my Swift books and bundles! >>

Working on autosave method, looking for optimization ideas

Forums > Swift

So I'm working on a notepad-style application, and I'm trying to work out an autosave-type function to save the user the need to explicitly save (as well as avoid the risk of losing data during a crash if the view doesn't disappear or the app doesn't go to the background).

So far I've got the following listener set in viewDidLoad():

NotificationCenter.default.addObserver(self, selector: #selector(autosave), name: UITextView.textDidChangeNotification, object: nil)

At the start of the function I've got the following logic to determine if we should proceed with the save or not:

    // lastSaved is a private class property, set to Date?
        if (isAutoSave) {
            if let timestamp = lastSaved {
                if (DateInterval(start: timestamp, end: Date()).duration < 3) {
                    print("Too soon for autosave")
                    return // Bail if it's been less than 3 seconds since the last auto-save
                }
            }

            print("Proceeding with Autosave")

            lastSaved = Date() // Set the date and proceed
        }

Overall this is working pretty well, but there's one minor flaw in it—once the timer expires it requires another input to trigger the save. Is there a way to modify this so that we can set (and keep re-setting) a delay timer whenever a keypress is detected while editing the UITextView and run the save when the timer expires?

1      

Are you using a UIDocument subclass? That gets autosave for free if you set up change tracking and supply the proper handler.

2      

Ah, didn't know that! I haven't really worked with UIDocument yet; I've mostly been using Codable to export JSON via Data.write(to:) to save data from my applications so far. Will have to give that a closer look.

1      

Hacking with Swift is sponsored by RevenueCat

SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.

Learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.