Learner456
Learner456

Reputation: 43

The Right Way To Share Data Got From Server Across all View Controllers?

I'm working on the Authentication Part of my app flow. So in the Login View Controller when the user taps the Login Button, network requests for the UserId. If a UserId is verified, then the user can Login. The Thing is all view controllers in my application are going to make network requests with that UserId , so I need a way to make the UserId accessible to all view controllers . How do I achieve that ?

Also what am I doing wrong? How would a Pro-Developer go with this situation ? Thanks for any help. Please also you can also share online resources. Thanks !!

Upvotes: 1

Views: 54

Answers (2)

Sneha
Sneha

Reputation: 880

You can save the userID & other User details you want to save through out the app by saving these in NSUserDefaults

var userID = "user1"
UserDefaults.standard.set(userID, forKey: "userID")

Now , whenever & In whichever screen you want to access these details, you can access like this.

if let userId = UserDefaults.standard.string(forKey: "userID") {
    // use details here...
}

Upvotes: 0

RJ168
RJ168

Reputation: 1046

It all depends on your requirement like:

  • If you don't want to persist UserId after app kill then you can use Singleton Class
  • If you want to persist UserId after app kill and you are not so concern about the security then can use UserDefault
  • If you want to persist UserId after app kill and you also wanted to follow guidelines to save sensitive data then can use Keychain

There are more options to use like Database FileWrite, so you need to choose wisely based upon your requirement.

You can find tons of tutorials for all above points

Upvotes: 1

Related Questions