I think that my problem is not that hard to solve. I must be missing out on something. I let my users login with Facebook so in the Application settings I have an option to logout from Facebook with an on/off switch. My Root.plist in Settings.bundle looks like this:
<dict>
<key>PreferenceSpecifiers</key>
<array>
<dict>
<key>Title</key>
<string></string>
<key>Type</key>
<string>PSGroupSpecifier</string>
</dict>
<dict>
<key>DefaultValue</key>
<false/>
<key>Key</key>
<string>facebookLogoutTriggered</string>
<key>Title</key>
<string>Logout Facebook</string>
<key>Type</key>
<string>PSToggleSwitchSpecifier</string>
</dict>
</array>
<key>StringsTable</key>
<string>Root</string>
</dict>
So basically the functionality I’m after is that if the user switches the switch to ON, he should be logged out from Facebook. After he has been logged out the switch should switched back to OFF. So I want OFF to be the default value of the switch.
Since booleans default to NO (OFF) I’m thinking I don’t need to use NSUserDefault´s registerDefaults:
So I check in applicationWillEnterForeground: if the user has turned the switch to on in App Settings by checking this:
// Check if the user wants to logout from Facebook
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
BOOL facebookLogoutTriggered = [defaults boolForKey:@"facebookLogoutTriggered"];
// Set "Logout Facebook" setting to OFF (NO)
[defaults setBool:NO forKey:@"facebookLogoutTriggered"];
[defaults synchronize];
But for some reason this code doesn’t seem to work. Most of the time it works (swith is switched off after the check). But sometimes i.e after logging in to Facebook it will set the switch to on for some reason. The code I run after logging in to Facebook is this:
#pragma mark - FBSessionDelegate Methods
- (void)fbDidLogin {
DLog(@"User logged in to Facebook.");
AppDelegate *appDelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
// Save accesstoken and expirationdate
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[appDelegate.facebook accessToken] forKey:@"FBAccessTokenKey"];
[defaults setObject:[appDelegate.facebook expirationDate] forKey:@"FBExpirationDateKey"];
[defaults synchronize];
DLog(@"defaults %@", [defaults objectForKey:@"facebookLogoutTriggered"]);
}
Been trying to fix this for 6 hours now but can’t really proceed any further.
For some reason, it seems that I have to do a
[[NSUserDefaults standardUserDefaults] synchronize];after the user has set an application setting. I only thought you had to call-synchronizedirectly after you are saving your values toNSUserDefaultsbut apparently it seems that you have to call it directly after retrieving yourNSUserDefaultsIF the user has set a preference in the Application settings (Settings.bundle).So instead of doing:
I now do: