A logout button should do three things: sign out of each login SDK (GIDSignIn.sharedInstance.signOut(), LoginManager().logOut()), delete the keys that belong to the session, and replace the screen stack with the login screen. Don't call removePersistentDomain(forName:) for this: Apple's documentation says it removes all of the keys and values in the domain, so settings like "onboarding seen" or the chosen language go too. synchronize() isn't needed; Apple calls it unnecessary. Tokens belong in the Keychain, not in UserDefaults. A tested SessionStore below removes only session keys.
SWIFT TIPS · LOGIN · USERDEFAULTS
First posted on May 23, 2018, as "LogOut FaceBook, Google & UserDefault Swift 4". Rewritten on November 19, 2026. The SessionStore code was compiled and run as a Mac Catalyst program with Swift 6.2.3 (Xcode 26.2, Swift 5 mode), using an in-memory store instead of real UserDefaults and fake sign-out providers. Nothing was written to this Mac's preferences or Keychain. The UserDefaults facts are from Apple's documentation.
In 2018 the post gave one button action for logging out of everything. It called GIDSignIn.sharedInstance().signOut() and FBSDKLoginManager().logOut(), removed the "userToken" key from UserDefaults, set a new LoginViewController as the navigation stack, then called removePersistentDomain(forName: Bundle.main.bundleIdentifier!) and synchronize(). Below it, the post quoted an article about clearing NSUserDefaults key by key.
The order of ideas is right: sign out of the providers, clear local data, go back to login. Two of the calls do more than a logout should, and one does nothing useful. This rewrite explains each call and gives a version that clears only what belongs to the user who's leaving.
What each 2018 call does
GIDSignIn ... signOut()is still right, spelledGIDSignIn.sharedInstance.signOut()today. Google's guide says it clears the SDK's sign-in state and your app's Keychain credentials for Google, and your app has to update its own UI.FBSDKLoginManager().logOut()is nowLoginManager().logOut(). In the current SDK it clears the access token, the authentication token and the profile.removeObject(forKey: "userToken")deletes one key. That's the right kind of call. The problem is the key: a login token in UserDefaults is stored in a plain file in the app's container.removePersistentDomain(forName:)with the bundle identifier wipes the app's whole defaults domain. Apple's documentation says the method removes all of the keys and values from the specified domain. Settings that have nothing to do with the account, like a theme, a language choice or whether onboarding was seen, disappear at logout.synchronize(): Apple's documentation for it says the method is unnecessary and shouldn't be used. UserDefaults saves on its own.
The 2018 code also replaced the stack before clearing defaults. It worked, but clearing first means the login screen never sees old data if it reads defaults in viewDidLoad.
Clear only the session
The fix is to know which keys belong to the session. Put them in one enum and remove exactly those:
import Foundation
/// Anything that can store small values. UserDefaults fits; tests use a dictionary.
protocol KeyValueStore: AnyObject {
func object(forKey key: String) -> Any?
func set(_ value: Any?, forKey key: String)
func removeObject(forKey key: String)
}
extension UserDefaults: KeyValueStore {}
/// Something that signs a user out of one provider (Google, Facebook, your own API).
protocol SignOutProvider {
var name: String { get }
func signOut()
}
final class SessionStore {
/// Every key that belongs to the logged-in user, and nothing else.
enum Key: String, CaseIterable {
case userID = "session.userID"
case displayName = "session.displayName"
case lastSyncDate = "session.lastSyncDate"
}
private let defaults: KeyValueStore
private let providers: [SignOutProvider]
init(defaults: KeyValueStore, providers: [SignOutProvider]) {
self.defaults = defaults
self.providers = providers
}
func logOut() {
providers.forEach { $0.signOut() }
Key.allCases.forEach { defaults.removeObject(forKey: $0.rawValue) }
// Tokens live in the Keychain, not here: delete them with your Keychain wrapper too.
}
}
The store is a protocol so the class works with UserDefaults.standard in the app and with a dictionary in a test. Each login SDK goes behind a small SignOutProvider, so the session code doesn't import Google or Facebook. I ran it with an in-memory store holding three session keys and two settings, and two fake providers:
before: ["session.displayName", "session.lastSyncDate", "session.userID", "settings.hasSeenOnboarding", "settings.language"]
signOut called: Google
signOut called: Facebook
after: ["settings.hasSeenOnboarding", "settings.language"]
Both providers were signed out, the three session. keys are gone, and the onboarding flag and language setting stayed. With removePersistentDomain, all five keys would have been removed.
Tokens go in the Keychain
The 2018 app kept its API token in UserDefaults under "userToken". UserDefaults is a property list in the app's container, meant for preferences. A token that lets someone act as the user belongs in the Keychain, which iOS encrypts and protects with the device passcode. Apple's Keychain Services documentation covers adding, finding and deleting items with SecItemAdd, SecItemCopyMatching and SecItemDelete. Most apps wrap those calls in a small type; the logout then calls its delete method next to removeObject. I didn't run Keychain code for this post.
Google and Facebook already keep their own tokens in the Keychain, which is why their sign-out calls are enough for them.
The button
With the pieces above, the button action is short. In a project with the flow object from the Google navigation post, it's:
@IBAction private func logOutTapped(_ sender: UIButton) {
sessionStore.logOut() // providers + session keys
authFlow.showLogin() // replaces the stack with a fresh login screen
}
Tell your server too, if it issues its own tokens, so the token stops working even if a copy exists somewhere. That's a request to your own API, made before or alongside the local cleanup.
A quick check for your project
- Search for
removePersistentDomainandsynchronize(). The first probably deletes settings at logout; the second can go. - List every UserDefaults key your app writes and mark which belong to the account.
- Search UserDefaults keys for "token", "password" or "secret". Move those to the Keychain.
What the 2018 version said
The post had no screenshots. After the code, it quoted several paragraphs and a code sample from another blog about clearing NSUserDefaults with removeObjectForKey and removePersistentDomainForName; I left the quote out and summarized the point above.
Keep reading on JR Devhub
Comments