Unable to get String value from UserDefaults - ios

Unable to get the string value stored in UserDefaults
var videoString = String()
In view did load
videoString = "http://site4brandz.com/cphp/26/uploads/oggy.mp4"
UserDefaults.standard.set(videoString as String, forKey: CurrentURL)
UserDefaults.standard.synchronize()
print("\(UserDefaults.standard.object(forKey: CurrentURL))")
It's printing as follows:
Optional(http://site4brandz.com/cphp/26/uploads/oggy.mp4)
When I go back and checking the same string like
if (UserDefaults.standard.value(forKey: CurrentURL) != nil) {
print("\(UserDefaults.standard.value(forKey: CurrentURL))")
let runningSrtring = UserDefaults.standard.value(forKey: CurrentURL)!
}
But now it's printing as Optional(4.067826) where did I made a mistake?

In Swift3
How about use UserDefaults.standard.string(forKey: CurrentURL)!
instead UserDefaults.standard.value(forKey: CurrentURL)!

Change your UserDefaults set code:
from:
UserDefaults.standard.set(videoString as String, forKey: CurrentURL)
to
if videoString {
UserDefaults.standard.set(videoString!, forKey: CurrentURL)
}
and check the different!

in Swift 2.3
you can set value string in UserDefaults
NSUserDefaults.standardUserDefaults().setObject(videoString, forKey: CurrentURL)
By get the value from
if let string = NSUserDefaults.standardUserDefaults().stringforKey(CurrentURL) {
}
In Swift 3
you can set value string in UserDefaults
UserDefaults.standard.set(videoString, forKey: CurrentURL)
By get the value from UserDefaults
if let string = UserDefaults.standard.string(forKey: CurrentURL) {
}
Make sure your key "CurrentURL" have same Value

Try it with Swift3:
extension UserDefaults {
func setValue(value: String, key: String) {
set(value, forKey: key)
synchronize()
}
func getValue(key: String) -> String {
return string(forKey: key)
}
}
Usage:
let videoString: String = "http://site4brandz.com/cphp/26/uploads/oggy.mp4"
UserDefaults.standard.setValue(value: videoString, key: CurrentURL)
and check it:
print(UserDefaults.standard.getValue(key: CurrentURL))
Notice that i am using key as a String. Change key's type to CurrentURL type as you expect (e.g: URL Type, ...)

Related

Filtering empty values from an API in swift

I'm trying to filter out empty and null values from an api in a json format in swift(UIKit).
The full data returns look like below but sometimes can contain null or empty values in the characteristic key. There is always going to be the same amount of keys.
//Cat
{
"breedname": "Persian",
"picture": "https://catimage.random.png",
"characteristic1": "Shy",
"characteristic2": "Hungry all the time"
"characteristic3": "Likes apples"
"characteristic4": "Grey color"
"characteristic5": "likes chin scratches"
}
{
"breedname": "Bengal",
"picture": "https://catimage.random.png",
"characteristic1": "Active",
"characteristic2": "Adventurous"
"characteristic3": ""
"characteristic4": ""
"characteristic5": ""
}
{
"breedname": "ragdoll",
"picture": "https://catimage.random.png",
"characteristic1": "Fiestey",
"characteristic2": "sharp claws"
"characteristic3": null
"characteristic4": null
"characteristic5": null
}
In order to filter null and empty values before showing in the UI, I have a Decodable class like below and a custom init class with the decodeifPresent method which changes null values to nill. However for empty values I just created a method which converts empty string values to nill. I'm not sure if there are better ways to handle empty and null data and filtering them out? I refer to all the Decodable keys in the UI so I cannot simply delete the keys themselves.
struct Cat: Decodable {
let breedName: String
let picture: String
let characteristic1 : String?
let characteristic2 : String?
let characteristic3 : String?
let characteristic4 : String?
let characteristic5 : String?
enum CodingKeys: String, CodingKey {
case breedName
case picture
case characteristic1
case characteristic2
case characteristic3
case characteristic4
case characteristic5
}
func checkEmpty(s: String?) -> String? {
if s == "" {
return nil
}
return s
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.breedName= try container.decode(String.self, forKey: .breedName)
self.picture = try container.decode(String.self, forKey: .picture)
self.characteristic1 = try container.decodeIfPresent(String.self, forKey: .characteristic1)
self.characteristic2 = try container.decodeIfPresent(String.self, forKey: .characteristic2)
self.characteristic3 = try container.decodeIfPresent(String.self, forKey: .characteristic3)
self.characteristic4 = try container.decodeIfPresent(String.self, forKey: .characteristic4)
self.characteristic5 = try container.decodeIfPresent(String.self, forKey: .characteristic5)
self.characteristic1 = checkEmpty(s: self.characteristic1)
self.characteristic2 = checkEmpty(s: self.characteristic2)
self.characteristic3 = checkEmpty(s: self.characteristic3)
self.characteristic4 = checkEmpty(s: self.characteristic4)
self.characteristic5 = checkEmpty(s: self.characteristic5)
One solution is to check for empty in a function defined in an extension to String
extension String {
func emptyAsNil() -> String? {
self.isEmpty ? nil : self
}
}
Then you could do all in one step in the init
self.characteristic1 = try container.decodeIfPresent(String.self, forKey: .characteristic1)?.emptyAsNil()
But perhaps a better solution is to gather all those properties in a collection like an array or a dictionary. Here I have chosen an array
struct Cat: Decodable {
let breedName: String
let picture: String
var characteristics: [String]
}
and then in the init we add only non-nil, non-empty values to the array
if let value = try container.decodeIfPresent(String.self, forKey: .characteristic1), !value.isEmpty {
characteristics.append(value)
}
or another way is to loop over the keys
let keys: [CodingKeys] = [.characteristic1,
.characteristic2,
.characteristic3,
.characteristic4,
.characteristic5]
for key in keys {
if let value = try container.decodeIfPresent(String.self, forKey: key), !value.isEmpty {
characteristics.append(value)
}
}

appending value to a data array and saving in Userdefault swift

I am trying to add a value to an array and store in userdefaults but I got error intitialy when trying to append the new value to the value pulled. below is my code.
private func putArray(_ value: GMSAutocompletePrediction?, forKey key: String) {
guard let value = value else {
return
}
let newArray = getArray(forKey: key)?.append(value) // error here
storage.setValue(NSKeyedArchiver.archivedData(withRootObject: value), forKey: key)
}
private func getArray(forKey key: String) -> [GMSAutocompletePrediction]? {
guard let data = storage.data(forKey: key) else { return nil}
return NSKeyedUnarchiver.unarchiveObject(with: data) as? [GMSAutocompletePrediction]
}
below is my error
Cannot use mutating member on immutable value: function call returns immutable value
The problem is getArray(forKey: key)? is immutable , you can't attach append directly to it , so you need
var newArray = getArray(forKey: key) ?? []
newArray.append(value)

How to save a Array with (Multiple Types) in NSUserDefaults

This is pretty simple but can't seem to find the correct information to solve saving an array like this in User Defaults.
It says it's not a property that NSUser Defaults Excepts.
Code:
var notificationList: [(type: String,imageName: String, text: String, date: String, seen: Bool)] = [(type: "Default",imageName: "ClearPartioned", text: "", date: "", seen: true)]
if (UserDefaults.standard.object(forKey: "notificationList")) == nil { // first time launching
print("making notification list")
UserDefaults.standard.set(notificationList, forKey: "notificationList")
UserDefaults.standard.synchronize()
print("\(notificationList)")
} else {
print("getting saved array")
notificationList = (UserDefaults.standard.object(forKey: "notificationList") as! [(type: String, imageName: String, text: String, date: String, seen: Bool)])
print("\(notificationList)")
}
Update:
This is closer but gives error found in this question here. These are the closet answers I have been able to find and there either out dated or crash the system.
Code:
if (UserDefaults.standard.object(forKey: "notificationList")) == nil { // first time launching
print("making notification list")
let encodedData = NSKeyedArchiver.archivedData(withRootObject: notificationList)
UserDefaults.standard.set(encodedData, forKey: "notificationList")
UserDefaults.standard.synchronize()
} else {
print("getting saved array")
notificationList = (UserDefaults.standard.object(forKey: "notificationList") as! [(type: String, imageName: String, text: String, date: String, seen: Bool)])
print("\(notificationList)")
}
Update 2: This is best answer implementation From Dhiru
Code:
if (UserDefaults.standard.object(forKey: "notificationList")) == nil { // first time launching
print("making notification list")
let notificationData = NSKeyedArchiver.archivedData(withRootObject: notificationList)
UserDefaults.standard.set(notificationData, forKey: "notificationList")
UserDefaults.standard.synchronize()
} else {
print("getting saved array")
let decodedData = UserDefaults.standard.object(forKey: "notificationList") as! Data
let notificationList = NSKeyedUnarchiver.unarchiveObject(with: decodedData) as AnyObject
print("\(notificationList)")
}
Its giving me an error that crashes system
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_SwiftValue encodeWithCoder:]: unrecognized selector sent to instance 0x1c011f380'
libc++abi.dylib: terminating with uncaught exception of type NSException
Im sure this code would fix it but this is horribly implemented with multiple errors below because I have no clue how to use this code.
Code:
func (coder aDecoder: NSCoder) {
if let notificationList = aDecoder.decodeObjectForKey("notificationList") {
self.notificationList = notificationList
}
}
func encodeWithCoder(aCoder: NSCoder) {
if let notificationList = notificationList {
aCoder.encodeObject(notificationList, forKey: "notificationList")
}
}
You have to store your Object in form of Data
Convert into data using
NSKeyedArchiver.archivedData(withRootObject:)
Convert back to Object using
NSKeyedUnarchiver.unarchiveObject(with:)
Saving Data for UserDefaults
let notificationData = NSKeyedArchiver.archivedData(withRootObject: notificationList)
UserDefaults.standard.set(notificationData, forKey: "notificationList")
Retrive Data from User UserDefaults
let decodedData = UserDefaults.standard.object(forKey: "notificationList") as! Data
let notificationList = NSKeyedUnarchiver.unarchiveObject(with: decodedData) as! AnyObject
This is how I actually save a Custom Object created in the app in Swift 4.
First, we create 3 protocols for our purpose of saving the custom object in UserDefaults. The logic behind is to convert the Custom Object into a normalized Dictionary/Array form.
This can be applied to any kind of Object which you have created.
The 3 protocols are:
Decoder (Used to decode the dictionary into custom object)
Encoder (Used to encode the custom object into dictionary)
UserDefaultsProtocol (Used to save, delete, update & retrieve the custom object from UserDefault)
Decoder Protocol
protocol Decoder {
associatedtype T
static func decode(dictionary: [String: Any]) -> T
}
Encoder Protocol
protocol Encoder {
func encode() -> [String: Any]
}
UserDefaultsProtocol
protocol UserDefaultsDelegate: class {
associatedtype T
func saveToUserDefaults()
static func removeFromUserDefaults()
static func retrieveFromUserDefaults() -> T?
}
As per your question, NotificationList Object would look like this
class NotificationList {
var type: String = ""
var imageName: String = ""
var text: String = ""
var date: String = ""
var seen: Bool = false
}
Now, you need to confirm all the 3 mentioned protocols to NotificationList. (Swift Best Practice: Use of Extensions & Protocols)
class NotificationList {
private struct Constants {
static let RootKey = "notification_list"
static let TypeKey = "type"
static let ImageNameKey = "image_name"
static let TextKey = "text"
static let DateKey = "date"
static let SeenKey = "seen"
}
var type: String = ""
var imageName: String = ""
var text: String = ""
var date: String = ""
var seen: Bool = false
typealias T = NotificationList
}
extension NotificationList: Encoder {
func encode() -> [String : Any] {
return [
Constants.TypeKey: type,
Constants.ImageNameKey: imageName,
Constants.TextKey: text,
Constants.DateKey: date,
Constants.SeenKey: seen
]
}
}
extension NotificationList: Decoder {
static func decode(dictionary: [String: Any]) -> NotificationList {
let type = dictionary[Constants.TypeKey] as! String
let imageName = dictionary[Constants.ImageNameKey] as! String
let text = dictionary[Constants.TextKey] as! String
let date = dictionary[Constants.DateKey] as! String
let seen = dictionary[Constants.SeenKey] as! Bool
let notificationList = NotificationList()
notificationList.type = type
notificationList.imageName = imageName
notificationList.text = text
notificationList.date = date
notificationList.seen = seen
return notificationList
}
}
extension NotificationList: UserDefaultsDelegate {
func saveToUserDefaults() {
UserDefaults.standard.setValue(encode(), forKey: Constants.RootKey)
}
static func retrieveFromUserDefaults() -> NotificationList? {
guard let encodedNotificationList = UserDefaults.standard.dictionary(forKey: Constants.RootKey) else {
return nil
}
return NotificationList.decode(dictionary: encodedNotificationList)
}
static func removeFromUserDefaults() {
UserDefaults.standard.removeObject(forKey: Constants.RootKey)
}
}
How to save NotificationList to UserDefaults?
var notificationList = NotificationList()
notificationList.type = "Default"
notificationList.imageName = "ClearPartioned"
notificationList.text = ""
notificationList.date = ""
notificationList.seen = true
Save to UserDefaults
notificationList.saveToUserDefaults()
Retrieve from UserDefaults
if let notificationList = NotificationList.retrieveFromUserDefaults() {
// You will get the instance of notification list saved in UserDefaults
}
HOW TO SAVE ARRAY OF NOTIFICATION LIST?
Say notificationLists contains the array of notificationList objects.
var notificationListsArray = [[String: Any]]()
notificationLists.forEach {
notificationListsArray.append($0.encode())
}
Save that array of dictionary to UserDefaults
UserDefaults.standard.setValue(notificationListsArray, forValue: "notificationLists")

How can I use UserDefaults in Swift?

How can I use UserDefaults to save/retrieve strings, booleans and other data in Swift?
ref: NSUserdefault objectTypes
Swift 3 and above
Store
UserDefaults.standard.set(true, forKey: "Key") //Bool
UserDefaults.standard.set(1, forKey: "Key") //Integer
UserDefaults.standard.set("TEST", forKey: "Key") //setObject
Retrieve
UserDefaults.standard.bool(forKey: "Key")
UserDefaults.standard.integer(forKey: "Key")
UserDefaults.standard.string(forKey: "Key")
Remove
UserDefaults.standard.removeObject(forKey: "Key")
Remove all Keys
if let appDomain = Bundle.main.bundleIdentifier {
UserDefaults.standard.removePersistentDomain(forName: appDomain)
}
Swift 2 and below
Store
NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "yourkey")
NSUserDefaults.standardUserDefaults().synchronize()
Retrieve
var returnValue: [NSString]? = NSUserDefaults.standardUserDefaults().objectForKey("yourkey") as? [NSString]
Remove
NSUserDefaults.standardUserDefaults().removeObjectForKey("yourkey")
Register
registerDefaults: adds the registrationDictionary to the last item in every search list. This means that after NSUserDefaults has looked for a value in every other valid location, it will look in registered defaults, making them useful as a "fallback" value. Registered defaults are never stored between runs of an application, and are visible only to the application that registers them.
Default values from Defaults Configuration Files will automatically be registered.
for example detect the app from launch , create the struct for save launch
struct DetectLaunch {
static let keyforLaunch = "validateFirstlunch"
static var isFirst: Bool {
get {
return UserDefaults.standard.bool(forKey: keyforLaunch)
}
set {
UserDefaults.standard.set(newValue, forKey: keyforLaunch)
}
}
}
Register default values on app launch:
UserDefaults.standard.register(defaults: [
DetectLaunch.isFirst: true
])
remove the value on app termination:
func applicationWillTerminate(_ application: UIApplication) {
DetectLaunch.isFirst = false
}
and check the condition as
if DetectLaunch.isFirst {
// app launched from first
}
UserDefaults suite name
another one property suite name, mostly its used for App Groups concept, the example scenario I taken from here :
The use case is that I want to separate my UserDefaults (different business logic may require Userdefaults to be grouped separately) by an identifier just like Android's SharedPreferences. For example, when a user in my app clicks on logout button, I would want to clear his account related defaults but not location of the the device.
let user = UserDefaults(suiteName:"User")
use of userDefaults synchronize, the detail info has added in the duplicate answer.
Best way to use UserDefaults
Steps
Create extension of UserDefaults
Create enum with required Keys to
store in local
Store and retrieve the local data wherever you want
Sample
extension UserDefaults{
//MARK: Check Login
func setLoggedIn(value: Bool) {
set(value, forKey: UserDefaultsKeys.isLoggedIn.rawValue)
//synchronize()
}
func isLoggedIn()-> Bool {
return bool(forKey: UserDefaultsKeys.isLoggedIn.rawValue)
}
//MARK: Save User Data
func setUserID(value: Int){
set(value, forKey: UserDefaultsKeys.userID.rawValue)
//synchronize()
}
//MARK: Retrieve User Data
func getUserID() -> Int{
return integer(forKey: UserDefaultsKeys.userID.rawValue)
}
}
enum for Keys used to store data
enum UserDefaultsKeys : String {
case isLoggedIn
case userID
}
Save in UserDefaults where you want
UserDefaults.standard.setLoggedIn(value: true) // String
UserDefaults.standard.setUserID(value: result.User.id!) // String
Retrieve data anywhere in app
print("ID : \(UserDefaults.standard.getUserID())")
UserDefaults.standard.getUserID()
Remove Values
UserDefaults.standard.removeObject(forKey: UserDefaultsKeys.userID)
This way you can store primitive data in best
Update
You need no use synchronize() to store the values. As #Moritz pointed out the it unnecessary and given the article about it.Check comments for more detail
Swift 4 :
Store
UserDefaults.standard.set(object/value, forKey: "key_name")
Retrive
var returnValue: [datatype]? = UserDefaults.standard.object(forKey: "key_name") as? [datatype]
Remove
UserDefaults.standard.removeObject(forKey:"key_name")
UserDefault+Helper.swift
import UIKit
private enum Defaults: String {
case countryCode = "countryCode"
case userloginId = "userloginid"
}
final class UserDefaultHelper {
static var countryCode: String? {
set{
_set(value: newValue, key: .countryCode)
} get {
return _get(valueForKay: .countryCode) as? String ?? ""
}
}
static var userloginId: String? {
set{
_set(value: newValue, key: .userloginId)
} get {
return _get(valueForKay: .userloginId) as? String ?? ""
}
}
private static func _set(value: Any?, key: Defaults) {
UserDefaults.standard.set(value, forKey: key.rawValue)
}
private static func _get(valueForKay key: Defaults)-> Any? {
return UserDefaults.standard.value(forKey: key.rawValue)
}
static func deleteCountryCode() {
UserDefaults.standard.removeObject(forKey: Defaults.countryCode.rawValue)
}
static func deleteUserLoginId() {
UserDefaults.standard.removeObject(forKey: Defaults.userloginId.rawValue)
}
}
Usage:
Save Value:
UserDefaultHelper.userloginId = data["user_id"] as? String
Fetch Value:
let userloginid = UserDefaultHelper.userloginId
Delete Value:
UserDefaultHelper.deleteUserLoginId()
I would say Anbu's answer perfectly fine but I had to add guard while fetching preferences to make my program doesn't fail
Here is the updated code snip in Swift 5
Storing data in UserDefaults
#IBAction func savePreferenceData(_ sender: Any) {
print("Storing data..")
UserDefaults.standard.set("RDC", forKey: "UserName") //String
UserDefaults.standard.set("TestPass", forKey: "Passowrd") //String
UserDefaults.standard.set(21, forKey: "Age") //Integer
}
Fetching data from UserDefaults
#IBAction func fetchPreferenceData(_ sender: Any) {
print("Fetching data..")
//added guard
guard let uName = UserDefaults.standard.string(forKey: "UserName") else { return }
print("User Name is :"+uName)
print(UserDefaults.standard.integer(forKey: "Age"))
}
//Save
NSUserDefaults.standardUserDefaults().setObject("yourString", forKey: "YourStringKey")
//retrive
let yourStr : AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("YourStringKey")
You can use NSUserDefaults in swift this way,
#IBAction func writeButton(sender: UIButton)
{
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("defaultvalue", forKey: "userNameKey")
}
#IBAction func readButton(sender: UIButton)
{
let defaults = NSUserDefaults.standardUserDefaults()
let name = defaults.stringForKey("userNameKey")
println(name) //Prints defaultvalue in console
}
Swift 5 and above:
let defaults = UserDefaults.standard
defaults.set(25, forKey: "Age")
let savedInteger = defaults.integer(forKey: "Age")
defaults.set(true, forKey: "UseFaceID")
let savedBoolean = defaults.bool(forKey: "UseFaceID")
defaults.set(CGFloat.pi, forKey: "Pi")
defaults.set("Your Name", forKey: "Name")
defaults.set(Date(), forKey: "LastRun")
let array = ["Hello", "World"]
defaults.set(array, forKey: "SavedArray")
let savedArray = defaults.object(forKey: "SavedArray") as? [String] ?? [String()
let dict = ["Name": "Your", "Country": "YourCountry"]
defaults.set(dict, forKey: "SavedDict")
let savedDictionary = defaults.object(forKey: "SavedDictionary") as? [String: String] ?? [String: String]()
:)
I saved NSDictionary normally and able to get it correctly.
dictForaddress = placemark.addressDictionary! as NSDictionary
let userDefaults = UserDefaults.standard
userDefaults.set(dictForaddress, forKey:Constants.kAddressOfUser)
// For getting data from NSDictionary.
let userDefaults = UserDefaults.standard
let dictAddress = userDefaults.object(forKey: Constants.kAddressOfUser) as! NSDictionary
I have Created my Custom Functions for Store Data in Userdefualts
//******************* REMOVE NSUSER DEFAULT *******************
func removeUserDefault(key:String) {
UserDefaults.standard.removeObject(forKey: key);
}
//******************* SAVE STRING IN USER DEFAULT *******************
func saveInDefault(value:Any,key:String) {
UserDefaults.standard.setValue(value, forKey: key);
UserDefaults.standard.synchronize();
}
//******************* FETCH STRING FROM USER DEFAULT *******************
func fetchString(key:String)->AnyObject {
if (UserDefaults.standard.object(forKey: key) != nil) {
return UserDefaults.standard.value(forKey: key)! as AnyObject;
}
else {
return "" as AnyObject;
}
}
class UserDefaults_FavoriteQuote {
static let key = "appname.favoriteQuote"
static var value: String? {
get {
return UserDefaults.standard.string(forKey: key)
}
set {
if newValue != nil {
UserDefaults.standard.set(newValue, forKey: key)
} else {
UserDefaults.standard.removeObject(forKey: key)
}
}
}
}
In class A, set value for key:
let text = "hai"
UserDefaults.standard.setValue(text, forKey: "textValue")
In class B, get the value for the text using the key which declared in class A and assign it to respective variable which you need:
var valueOfText = UserDefaults.value(forKey: "textValue")
Swift 4,
I have used Enum for handling UserDefaults.
This is just a sample code. You can customize it as per your requirements.
For Storing, Retrieving, Removing.
In this way just add a key for your UserDefaults key to the enum.
Handle values while getting and storing according to dataType and your requirements.
enum UserDefaultsConstant : String {
case AuthToken, FcmToken
static let defaults = UserDefaults.standard
//Store
func setValue(value : Any) {
switch self {
case .AuthToken,.FcmToken:
if let _ = value as? String {
UserDefaults.standard.set(value, forKey: self.rawValue)
}
break
}
UserDefaults.standard.synchronize()
}
//Retrieve
func getValue() -> Any? {
switch self {
case .AuthToken:
if(UserDefaults.standard.value(forKey: UserDefaultsConstant.AuthToken.rawValue) != nil) {
return "Bearer "+(UserDefaults.standard.value(forKey: UserDefaultsConstant.AuthToken.rawValue) as! String)
}
else {
return ""
}
case .FcmToken:
if(UserDefaults.standard.value(forKey: UserDefaultsConstant.FcmToken.rawValue) != nil) {
print(UserDefaults.standard.value(forKey: UserDefaultsConstant.FcmToken.rawValue))
return (UserDefaults.standard.value(forKey: UserDefaultsConstant.FcmToken.rawValue) as! String)
}
else {
return ""
}
}
}
//Remove
func removeValue() {
UserDefaults.standard.removeObject(forKey: self.rawValue)
UserDefaults.standard.synchronize()
}
}
For storing a value in userdefaults,
if let authToken = resp.data?.token {
UserDefaultsConstant.AuthToken.setValue(value: authToken)
}
For retrieving a value from userdefaults,
//As AuthToken value is a string
(UserDefaultsConstant.AuthToken.getValue() as! String)
use UserDefault to store any settings value you want your application to remember between start ups, maybe you want to know ifs its been started before, maybe you want some values the user has set to be remembers so they don't have to be set very time, on Mac windows frames are stored in there for you, maybe you want to control the behaviour of the app, but you don't want it available to end users, you just want to choose just before your release. Be careful what you store in UserDefaults, it's not protected.

How to retrieve string from UserDefaults in Swift?

I have a textField for the user to input their name.
#IBAction func nameTextField(sender: AnyObject) {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("\(nameTextField)", forKey: "userNameKey")
}
Then I recall the inputted name in ViewDidLoad with:
NSUserDefaults.standardUserDefaults().stringForKey("userNameKey")
nameLabel.text = "userNameKey"
What am I doing wrong? Result is simply "userNameKey" every time. I'm new to this, thanks!
You just have to assign the result returned by nsuserdefaults method to your nameLabel.text. Besides that stringForKey returns an optional so I recommend using the nil coalescing operator to return an empty string instead of nil to prevent a crash if you try to load it before assigning any value to the key.
func string(forKey defaultName: String) -> String?
Return Value For string values, the string associated with the
specified key. For number values, the string value of the number.
Returns nil if the default does not exist or is not a string or number
value.
Special Considerations
The returned string is immutable, even if the value you originally set was a mutable string.
You have to as follow:
UserDefaults.standard.set("textToSave", forKey: "userNameKey")
nameLabel.text = UserDefaults.standard.string(forKey: "userNameKey") ?? ""
What you need to do is:
#IBAction func nameTextField(sender: AnyObject) {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.set(yourTextField.text, forKey: "userNameKey")
}
And later in the viewDidLoad:
let defaults = NSUserDefaults.standardUserDefaults()
let yourValue = defaults.string(forKey: "userNameKey")
nameLabel.text = yourValue

Resources