I have this class Signin which is initialized when the user signs in using username, password but it also gets and sets the uname, password to keychain. I'm going to use this Signin class everywhere else in the code but I dont want to create a new instance each time but as the user logs in for the first time, should be initialized and then throughout the app, that same instance should be used unless the user decides to sign out.
I declare and create a instance of this class in AppDelegate where my sign in code is.
var signin: SignIn?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
signin = SignIn(username: fullName!, password: "")
}
Here is how my class looks like:
class SignIn {
let username: String
let password: String
let keychain = KeychainSwift()
init(username: String, password: String) {
self.username = username
self.password = password
}
func getUsername() -> String {
if (keychain.get("username") != nil) {
return keychain.get("username")!
}
return ""
}
func setUsername(username: String) {
keychain.set(username, forKey: "username")
}
func getPassword() -> String {
if (keychain.get("password") != nil) {
return keychain.get("password")!
}
return ""
}
func setPassword(password: String) {
keychain.set(password, forKey: "password")
}
}
But when I try to access it lets say in a ViewController to say "welcome username". I do something like this:
class ViewController: UIViewController {
@IBOutlet weak var welcomeText: UITextField!
var signIn: SignIn?
override func viewDidLoad() {
let username: String = signIn!.getUsername()
welcomeText.text = "Welcome \(username)"
}
}
Is this the right way? How do I make the class in such a way that I get a shared instance of the Signin class and that same instance gets shared everywhere and while signing out, I uninitialize the class.