Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store global strings in iOS in Swift for app-wide use

Tags:

string

ios

swift

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

like image 809
Raghavendra Avatar asked Aug 18 '14 08:08

Raghavendra


2 Answers

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")
like image 118
Raghavendra Avatar answered Oct 24 '22 01:10

Raghavendra


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.

like image 24
jou Avatar answered Oct 24 '22 00:10

jou