Decide the first screen in your scene delegate's scene(_:willConnectTo:options:): if a saved session token exists, make Home the root view controller, otherwise Login. Keep the token in the Keychain, not in UserDefaults, which Apple says stores data unencrypted. When the user logs in or out, swap the window's root view controller instead of pushing screens on top of each other.
SWIFT TIPS · UIKIT
First posted on June 8, 2018 for Swift 4, as "skip login view Controller if you are already authorized? swift 4". Rewritten on November 17, 2026. The Swift code below was type-checked on a Mac with Xcode 26.2 against the iOS 26.2 SDK, in Swift 5 and Swift 6 language modes, with iOS 15 as the deployment target. It wasn't run, and the Keychain calls weren't exercised for this rewrite.
The 2018 answer did two things. The login button saved what the user typed into UserDefaults and pushed the Home screen. And didFinishLaunchingWithOptions in the App Delegate checked UserDefaults for a token, picked Home or Onboarding, and built the window by hand. It worked in the iOS 11 apps of that time.
Three things have changed since. Apps now set up their windows in a scene delegate. The token belongs somewhere safer than UserDefaults. And pushing Home on top of Login leaves the login screen one Back swipe away. Here is the whole flow as I'd build it now.
The code
import UIKit
import Security
/// Stores the access token in the Keychain instead of UserDefaults.
enum TokenStore {
private static let service = "com.example.myapp.session"
private static let account = "accessToken"
private static var baseQuery: [String: Any] {
[kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: account]
}
static func save(_ token: String) -> Bool {
let data = Data(token.utf8)
let status = SecItemUpdate(baseQuery as CFDictionary, [kSecValueData as String: data] as CFDictionary)
if status == errSecSuccess { return true }
guard status == errSecItemNotFound else { return false }
var add = baseQuery
add[kSecValueData as String] = data
add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
return SecItemAdd(add as CFDictionary, nil) == errSecSuccess
}
static func read() -> String? {
var query = baseQuery
query[kSecReturnData as String] = true
query[kSecMatchLimit as String] = kSecMatchLimitOne
var result: CFTypeRef?
guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess,
let data = result as? Data else { return nil }
return String(data: data, encoding: .utf8)
}
@discardableResult
static func delete() -> Bool {
let status = SecItemDelete(baseQuery as CFDictionary)
return status == errSecSuccess || status == errSecItemNotFound
}
}
final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession,
options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = scene as? UIWindowScene else { return }
let window = UIWindow(windowScene: windowScene)
window.rootViewController = makeRoot(signedIn: TokenStore.read() != nil)
window.makeKeyAndVisible()
self.window = window
}
func showHome() { switchRoot(signedIn: true) }
func showLogin() { switchRoot(signedIn: false) }
private func makeRoot(signedIn: Bool) -> UIViewController {
UINavigationController(rootViewController: signedIn ? HomeViewController() : LoginViewController())
}
private func switchRoot(signedIn: Bool) {
guard let window else { return }
UIView.transition(with: window, duration: 0.3, options: .transitionCrossDissolve) {
window.rootViewController = self.makeRoot(signedIn: signedIn)
}
}
}
final class LoginViewController: UIViewController {
func loginSucceeded(token: String) {
guard TokenStore.save(token) else { return }
(view.window?.windowScene?.delegate as? SceneDelegate)?.showHome()
}
}
final class HomeViewController: UIViewController {
func logOutTapped() {
TokenStore.delete()
(view.window?.windowScene?.delegate as? SceneDelegate)?.showLogin()
}
// When the server says the token is no longer valid
func handleUnauthorized() {
logOutTapped()
}
}
final class AppDelegate: UIResponder, UIApplicationDelegate {
private let launchedKey = "hasLaunchedBefore"
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Keychain items can outlive an uninstall. Start signed out after a fresh install.
if !UserDefaults.standard.bool(forKey: launchedKey) {
TokenStore.delete()
UserDefaults.standard.set(true, forKey: launchedKey)
}
return true
}
}
Pick the first screen in the scene delegate
Since iOS 13, an app with a scene manifest gets its windows from the scene delegate, and new Xcode projects are set up that way. scene(_:willConnectTo:options:) is where the 2018 window code moves to. It creates a UIWindow for the window scene, checks for a token, and sets Home or Login as the root before the first frame appears. The user never sees the login screen flash by.
If your app still has no scene delegate, this is worth doing soon. Apple's technote TN3187 says that iOS 26 logs "UIScene lifecycle will soon be required", and that in the next major release after iOS 26, apps built with the latest SDK must adopt the scene life cycle or they won't launch. Only the scene life cycle is required, not support for multiple windows.
Swap the root instead of pushing
After a successful login, the 2018 code pushed HomeViewController onto the navigation stack. That leaves Login underneath, so a swipe from the left edge takes the user back to the login form while they're signed in. showHome() and showLogin() replace the window's root view controller instead, with a short cross-dissolve so it doesn't feel abrupt. Logging out calls showLogin(), and so should any network response that says the token is no longer valid. That's what handleUnauthorized() is for.
Keep the token in the Keychain
Apple's documentation for UserDefaults says to store only nonsensitive information there, because the defaults system stores data on disk unencrypted, and to put personal or sensitive information in the Keychain instead. An access token is sensitive: anyone who copies it can act as that user until it expires.
TokenStore is a small wrapper around the Keychain functions:
savetriesSecItemUpdatefirst and only callsSecItemAddwhen nothing is stored yet. CallingSecItemAddfor an item that already exists fails witherrSecDuplicateItem, which is a common reason a second login "doesn't save".kSecAttrAccessibleAfterFirstUnlockThisDeviceOnlymakes the token readable after the device has been unlocked once since it started, which background refreshes need. Apple's documentation also says items with "ThisDeviceOnly" don't move to a new device through a backup. If your app only reads the token while it's open,kSecAttrAccessibleWhenUnlockedThisDeviceOnlyis stricter.deletetreats "not found" as success, so logging out twice isn't an error.
The AppDelegate at the end clears the token on the first launch after an install. Keychain items can survive deleting the app, so without this, someone who deletes and reinstalls your app may find themselves still signed in. Apple doesn't document that behavior either way, which is exactly why I'd rather not depend on it. I didn't test it on a device for this rewrite.
A token isn't proof the user is still signed in
The check in the scene delegate only knows that a token exists. The server may have revoked it, or it may have expired while the app was closed. Show Home right away so launch stays fast, then let the first request that comes back unauthorized send the user to Login. If your tokens have a known expiry date, you can also store that date next to the token and check it before choosing the first screen.
A quick check for your project
- Search for
UserDefaultstogether withtoken,passwordorsession. Each hit is something to move to the Keychain. - Check whether your Info.plist has
UIApplicationSceneManifest. If it doesn't, read TN3187 before your next SDK update. - Log in, then swipe from the left edge on the Home screen. If Login slides back in, swap the root instead of pushing.
What the 2018 version said
The original saved the login field with UserDefaults.standard.set(loginTextField.text, forKey: "login"), pushed Home, and in the App Delegate chose between HomeViewController and OnBoardingViewController by checking UserDefaults.standard.string(forKey: "token"). It used UIApplicationLaunchOptionsKey, the Swift 4 name of what is now UIApplication.LaunchOptionsKey. Type-checked with Xcode 26.2, the App Delegate part stops in both Swift 5 and Swift 6 mode with "'UIApplicationLaunchOptionsKey' has been renamed to 'UIApplication.LaunchOptionsKey'". The idea, deciding the first screen before anything is shown, is the same one the scene delegate uses above.
Keep reading on JR Devhub
Comments