如何确定何时在ios上更改设置

我使用标准的root.plist方法为iPhone创build了一个自定义设置。 我想知道是否有一种方法来确定当用户更改我的应用程序中的这些设置…

你可以用这个来监听NSUSerDefaultsDidChange-notifications:

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

每当NSUserDefaults改变, defaultsChanged将被调用。

不要忘记调用[[NSNotificationCenter defaultCenter] removeObserver:self]; 当你想停止听这些通知(你也应该这样做,当对象被释放)。

语法是Swift 2.使用Swift,你可以这样做来订阅NSUserDefaults的变化:

 NSNotificationCenter.defaultCenter().addObserver(self, selector: "defaultsChanged:", name: NSUserDefaultsDidChangeNotification, object: nil) 

然后创build这样的方法:

 func defaultsChanged(notification:NSNotification){ if let defaults = notification.object as? NSUserDefaults { //get the value for key here } } 

注册以接收NSUserDefaultsDidChangeNotification通知。 这并不明显,但iOS应用程序编程指南如此描述:

您的应用程序通过“设置”应用程序公开的首选项已更改

使用键“instantWeb”访问特定于应用程序的Booltypes设置的示例:

 func observeUserDefaults(notification: NSNotification) { print("Settings changed") if let defaults = notification.object as? NSUserDefaults { if defaults.valueForKey("instantWeb") as! Bool==true { print("Instant Web ON") } } } 

聆听设置中的更改

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

一旦这个视图控制器不在内存中,请记得移除观察者。

在iOS10中,试试这个:

 UNUserNotificationCenter.current().getNotificationSettings { (settings) in // Your code here }