nebekerdev
nebekerdev

Reputation: 142

Checking If user is logged in or not

I'm new to iOS development and to the AWS Amplify framework. I am currently working my way through the Authentication documentation, but it isn't clear how to check the logged-in status of a given user. I only want to display the login form if the user not already logged in. How do I achieve this? There doesn't seem to be any information listed in the docs, and the only resource I found from google applied to a different platform (react).

Upvotes: 1

Views: 1928

Answers (1)

Gerard Sans
Gerard Sans

Reputation: 2279

You need to listen to Auth events and update the state for a flag Eg:isSignedIn which would be initially signed off.

final class UserData: ObservableObject {
    @Published var isSignedIn : Bool = false
}
import UIKit
import Amplify
import AmplifyPlugins

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    public let userData = UserData()

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        do {
            try Amplify.add(plugin: AWSCognitoAuthPlugin())
            try Amplify.configure()
            
            // load data when user is signedin
            self.checkUserSignedIn()

            // listen to auth events
            _ = Amplify.Hub.listen(to: .auth) { (payload) in

                switch payload.eventName {

                case HubPayload.EventName.Auth.signedIn:
                    self.updateUI(forSignInStatus: true)

                case HubPayload.EventName.Auth.signedOut:
                    self.updateUI(forSignInStatus: false)
                    
                case HubPayload.EventName.Auth.sessionExpired:
                    self.updateUI(forSignInStatus: false)

                default:
                    break
                }
            }

        } catch {
            print("Failed to configure Amplify \(error)")
        }

        return true
    }
    func updateUI(forSignInStatus : Bool) {
        DispatchQueue.main.async() {
            self.userData.isSignedIn = forSignInStatus
        }
    }
    
    // when user is signed in, fetch its details
    func checkUserSignedIn() {

        // every time auth status changes, let's check if user is signedIn or not
        // updating userData will automatically update the UI
        _ = Amplify.Auth.fetchAuthSession { (result) in

            do {
                let session = try result.get()
                self.updateUI(forSignInStatus: session.isSignedIn)
            } catch {
                print("Fetch auth session failed with error - \(error)")
            }

        }
    }

See the full code here.

Upvotes: 3

Related Questions