Listen to auth events
Amplify Auth emits events during authentication flows, which enables you to react to user flows in real time and trigger custom business logic. For example, you may want to capture data, synchronize your app's state, and personalize the user's experience. You can listen to and respond to events across the Auth lifecycle such as sign-in and sign-out.
AWS Cognito Auth Plugin sends important events through Amplify Hub. You can listen to these events like the following:
override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view.
// Assumes `unsubscribeToken` is declared as an instance variable in your view unsubscribeToken = Amplify.Hub.listen(to: .auth) { payload in switch payload.eventName { case HubPayload.EventName.Auth.signedIn: print("User signed in") // Update UI
case HubPayload.EventName.Auth.sessionExpired: print("Session expired") // Re-authenticate the user
case HubPayload.EventName.Auth.signedOut: print("User signed out") // Update UI
case HubPayload.EventName.Auth.userDeleted: print("User deleted") // Update UI
default: break } }}
override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view.
// Assumes `sink` is declared as an instance variable in your view controller sink = Amplify.Hub .publisher(for: .auth) .sink { payload in switch payload.eventName { case HubPayload.EventName.Auth.signedIn: print("User signed in") // Update UI
case HubPayload.EventName.Auth.sessionExpired: print("Session expired") // Re-authenticate the user
case HubPayload.EventName.Auth.signedOut: print("User signed out") // Update UI
case HubPayload.EventName.Auth.userDeleted: print("User deleted") // Update UI
default: break } }}