Home > Blockchain >  Passing data/variable declared from HTTP request data to another View Controller
Passing data/variable declared from HTTP request data to another View Controller

Time:10-06

Summary:

In my login view controller for my first screen, I have it set up to where when a user hits "Sign in" it will run a function that takes in a username and password and POSTs those into my backend with an HTTP request. Then from that request in that function, in the response back there is a "user_id" within the data. I need to somehow set that "user_id" that comes back to a variable so that I can use it throughout the app. For example, whenever I make any requests in the app, I need that "user_id" to plug into URLs to fetch data for a user's account. I will include code snippets.

This first one is from my login function. As you can see from the last print, that is how to parse to get to the "user_id" from the response.

            let decoder = JSONDecoder()
            let loginResponse = try decoder.decode(LoginResponse.self, from: json)
            print(loginResponse.data)
            print(loginResponse.data.id)

This next one is from an instance where I need to take that "user_id" and plug it into a URL for another HTTP Request in another file.

    let resourceString = "https://*******.herokuapp.com/\(userID)/allergies"
    guard let resourceURL = URL(string: resourceString) else {fatalError()}

Any help would be much appreciated and let me know if I need to provide any more information.

CodePudding user response:

Normally you have more validation and security to reach the backend. Like, auth / bearer tokens / refresh tokens. I tend to save these in a Authenticator singleton which is used in my requestBuilder protocol.

If you want to save the userID even if they shut down the app for some time, then i agree with @luffy_064 that should save it in UserDefault or CoreData.

Since it's just 1 key, i would prefer UserDefault as it's quick and simple. Keychain is more of a lifetime thingy. Which i wouldn't suggest for an userid, but maybe if they want to save their password.

CodePudding user response:

Yes, you can save access token or user id in Userdefaults and check whether the user logged in or not or to use it in next request

UserDefaults.standard.set(loginResponse.data.id, forKey: "userId")

To get it use

let userId = UserDefaults.standard.value(forKey: "userId")
  • Related