I am trying to maintain a login record for a user in swift IOS application. I have a Login view controller in which after successfully logging in the user, i am posting a notification.
let infodict = ["userLoggedIn": true]
NotificationCenter.default.post(name:
NSNotification.Name(rawValue:"NotificationuserLoggedIn"), object: nil, userInfo: infodict)
And in viewdidload of my Home view controller, i am adding observer to it like
NotificationCenter.default.addObserver(self, selector:
#selector(self.toggleLoginButtonText(_:)), name:
NSNotification.Name(rawValue:"NotificationUserLoggedIn"), object: nil)
The observer will call the function "toggleLoginButtonText". And in this function i am toggling the text of a login button. If user is logged in the button text should be "Log out" and "Log In" otherwise. Everything works fine till now.
The problem: I want that whenever the user logs out by pressing the button, i update the user info of the the same notification. And then i viewwillappear function of my home controller, i will call "toggleLoginButtonText" function and it will check for notification value. if value of "userLoggedIn" (because user logged out), my function will change the text of login button.
So summing up, My question is two fold.
- How to update my notification's userinfo when user logs in and logs out
Is this a good way of handling user logged in record, or there are better ways than this?
I have one more idea in my mind. "when user logs out, post another notification and observer it in my home controller, and when user logs in again, post another notifiaction, so on and so forth". but i seems a repetitive task to me.
I have looked for answers to these questions. But there are only answers for how to pass data using notifications which i have already passed.
How to pass data using NotificationCentre in swift 3.0 and NSNotificationCenter in swift 2.0?
How to pass data using NotificationCentre in swift 3.0 and NSNotificationCenter in swift 2.0?