How to know when user made change to settings bundle

后端 未结 3 1005
我在风中等你
我在风中等你 2021-02-20 09:42

I let the user make changes to their settings in the settings area of the iphone. During the next network sync i\'d like to send the user changes to the server. But only if the

相关标签:
3条回答
  • 2021-02-20 10:03

    Ah silly me! Here we go with an elegant way. Search for AppPrefs in the Apple Documentation within XCode and it'll show an example app which does exactly what you want to do. Just compile and run! It makes use of the NSUserDefaultsDidChangeNotification.

    This is the code being used to register an observer:

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(defaultsChanged:)
                                                 name:NSUserDefaultsDidChangeNotification
                                               object:nil];
    

    Old answer:

    It doesn't look like as if you could get a modification date out of the NSUserDefaults. So far I only can think of this way:

    NSUserDefaults *previousDefaults = [someInstance previousUserDefaults];
    NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
    
    if([previousDefaults isEqualToDictionary:currentDefaults]) 
    {
        [someOtherInstance sendModifiedUserDefaultsToServerWithDefaults:currentDefaults];
        [yetAnotherInstance saveModified]
    }
    

    You have to save the user defaults yourself as dictionary to disk when the app is launched the first time: your default values. Then, everytime the app is opened you compare those two dictionaries. If they

    0 讨论(0)
  • 2021-02-20 10:04

    It's not that the question is too hard, it's just that there's not a simple way to do what you're asking. NSUserDefaults doesn't record a "last modified" date for each app's settings, at least as far as I can tell, so if the user changes some settings using the Settings app, there's not a good way to detect that other than to look at all the settings.

    If you really need to do this, I think your best bet is to read the settings that you're interested in syncing into some data structure and calculating some sort of hash or checksum based on that structure. Compare that value to the value that you calculated the last time the app ran, and sync with the server if it's different. You can store that value in NSUserDefaults if you want, but make sure that you don't include it in the calculation.

    0 讨论(0)
  • 2021-02-20 10:18

    Swift

    Observe for changes and call a method on change:

    NotificationCenter.default.addObserver(
        self,
        selector: #selector(updateStateFromSettingsBundle),
        name: UserDefaults.didChangeNotification,
        object: nil
    )
    
    @objc func updateStateFromSettingsBundle() {}
    
    0 讨论(0)
提交回复
热议问题