I am designing an app which has a login screen. When the user enters username and password, a call to web service is done which returns a token on successful login. Now I need to send this token to every HTTP call inside different screens across the app.
I want to achieve similar functionality like this: Where to store global constants in an iOS application?
As there won't be any .h
and .m
files in Swift, how do I store these global strings (Note these are not constants, these are global variables) that I need to be able to access in any view controller
This is what exactly I wanted: Sharing strings and variables throughout ios app
I am able to share strings such as apikeys, tokens by using NSUserDefaults
saving:
NSUserDefaults.standardUserDefaults().setObject("apistringhere", forKey: "apikey")
NSUserDefaults.standardUserDefaults().synchronize()
getting:
NSUserDefaults.standardUserDefaults().objectForKey("apikey")
First off, using global variable is not the right answer to most questions. You should rather have an object that takes care of communicating with the web service and that object should also be responsible to tracking login state and tokens. If URLs changes, you'd have to only change them in one place and the code processing the data doesn't need to care where the data come from.
That being said, you can declare a global variable or constant in Swift just by declaring at the top level scope of a file, outside of any functions, methods, closures or types. You can also modify the visibility of the variable/constant with the access control keywords.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With