I am saving data into userDeafults using 2 textfield as String, String but I want to know how to retrieve all the data to display either using loop or function
let save = UserDefaults.standard
let heading = headingText.text
let description = desxriptionTexr.text
save.set(description, forKey: heading!)
To get all keys and corresponding values in UserDefaults, you can use:
for (key, value) in UserDefaults.standard.dictionaryRepresentation() {
print("\(key) = \(value) \n")
}
In swift 3, you can store and retrieve using:
UserDefaults.standard.setValue(token, forKey: "user_auth_token")
print("\(UserDefaults.standard.value(forKey: "user_auth_token")!)")
I think is not a correct way to do.
I suggest you to put your values into a dictionary and set the dictionary into the UserDefaults.
let DictKey = "MyKeyForDictionary"
var userDefaults = UserDefaults.standard
// create your dictionary
let dict: [String : Any] = [
"value1": "Test",
"value2": 2
]
// set the dictionary
userDefaults.set(dict, forKey: DictKey)
// get the dictionary
let dictionary = userDefaults.object(forKey: DictKey) as? [String: Any]
// get value from
let value = dictionary?["value2"]
// iterate on all keys
guard let dictionary = dictionary else {
return
}
for (key, val) in dictionary.enumerated() {
}
If you have multiple Strings, simply save value as array
UserDefaults.standard.set(YourStringArray, forKey: "stringArr")
let arr = UserDefaults.standard.stringArray(forKey: "stringArr")
for s in arr! {
//do stuff
}
Here you are setting the key as heading and the value as description.
You can retrieve the value from userDefaults using UserDefaults.standard.object(forKey:), UserDefaults.standard.string(forKey: ),UserDefaults.standard.value(forKey: ) etc functions.
So its better to save heading and description for 2 different keys may be like
let save = UserDefaults.standard
let heading = headingText.text
let description = desxriptionTexr.text
save.set(description, forKey: "description")
save.set(heading, forKey: "heading")
And you could retrieve like
let description = UserDefaults.standard.string(forKey:"description")
let heading = UserDefaults.standard.string(forKey:"heading")
Related
I am newly to Swift programming. I am developing an app where I have an array of Objects that I need to save it into one Dictionary, means for Dictionary 'Array of Objects' should be my Value and 'ID' should be my Key.
Here 2 elements contains in my Array, how can I save and retrieve from Dictionary using any unique Key. Please suggest me. Thank you!
You can do it by
var myDict = Dictionary<String, Any>()
myDict = ["myKey": myArrayObjectName as! VideoRangeInfo]
Now you can access you array by use "myKey" of dictionary like below,
print("My array = \(myDict["myKey"] as! VideoRangeInfo)")
UPDATED: I think your array is objective c NSMutableArray not swift Array so
var myDic = NSMutableDictionary()
myDic.setObject(myArrayObjectName, forKey: "myKey")
And
print("My array = \(myDic.object(forKey: "MyKey") as! VideoRangeInfo)")
One simple approach is:
struct VideoRangeInfo {
var name: String
}
var arrayVideoRange = [
VideoRangeInfo(name: "Name1"),
VideoRangeInfo(name: "Name2"),
VideoRangeInfo(name: "Name3")
]
var dictionary = [String: VideoRangeInfo]()
for obj in arrayVideoRange {
dictionary.updateValue(obj, forKey: obj.name)
}
print(dictionary["Name1"]!)
print(dictionary["Name2"]!)
print(dictionary["Name3"]!)
Saving
var dictionary = Int:String
dictionary.updateValue(value: self.arrangeVideoInfo[0]!, forKey: 1)
dictionary.updateValue(value: self.arrangeVideoInfo[0]!, forKey: 2)
Getting
let value1 = dictionary[1] as! VideoRangeInfo
let value2 = dictionary[2] as! VideoRangeInfo
I am trying to store an array to NSUserDefaults and retrieve the array when needed to populate a UITableView.
Currently I am using:
//store data
NSUserDefaults.standardUserDefaults().setObject(myArray, forKey: "\(identity.text!)listA")
NSUserDefaults.standardUserDefaults().synchronize()
//retrieve data
let tabledata = NSUserDefaults.standardUserDefaults().stringForKey("\(identity.text!)listA")
myArray = [tabledata!]
tableView.reloadData()
But I get
fatal error: unexpectedly found nil while unwrapping an Optional
value
when trying to load the data. I am not sure if the issue is in the storage or the retrieval. Has anyone been through this before?
From your code I see you are storing some array
// Your code
NSUserDefaults.standardUserDefaults().setObject(myArray, forKey: "\(identity.text!)listA")
and retrieving a string
//Your code
let tabledata = NSUserDefaults.standardUserDefaults().stringForKey("\(identity.text!)listA")
There is probably a type mismatch, You store one type and retrieve another type.
While retrieving either use arrayForKey() or objectForKey() see the code below.
let tabledata = NSUserDefaults.standardUserDefaults().arrayForKey("\(identity.text!)listA")
or
let tabledata = NSUserDefaults.standardUserDefaults().objectForKey("\(identity.text!)listA")
If it is an array I would go with First one.
Here are the way that you can store and retrieved array of object with help of NSKeyArchive.
To Store array to NSUserDefault.
let placesData = NSKeyedArchiver.archivedData(withRootObject: placesArray)
UserDefaults.standard.set(placesData, forKey: "places")
To Retrieved array from NSUserDefault.
let placesData = UserDefaults.standard.object(forKey: "places") as? NSData
if let placesData = placesData {
let placesArray = NSKeyedUnarchiver.unarchiveObject(with: placesData as Data) as? [Place]
print(placesArray)
}
Hope this help you.
Saving and Retrieving a String array to UserDefaults
Save array
let array = ["horse", "cow", "camel", "sheep", "goat"]
let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedStringArray")
Retrieve array
let defaults = UserDefaults.standard
let array = defaults.object(forKey: "SavedStringArray") as? [String] ?? [String]()
See more at How to save user settings using NSUserDefaults
What are you storing in the array?
If it's objects it won't work, if It's just strings or numbers then it should be fine.
Next steps you take should be to turn on exception breakpoints and maybe println() everything you can so you can pinpoint the exact whereabouts of the problem.
As a shot in the dark I would suggest maybe (identity.text!) is coming out as nil
Also you should probably change it to this
if let tabledata: NSArray = NSUserDefaults.standardUserDefaults().stringForKey("\(identity.text!)listA"){
myArray = [tabledata!]
tableView.reloadData()
}
This will make the code not even try to run unless there is a value it can use
Latest swift3 version to store array of data into userdefaults and get that array of data using keys
let nameArray = ["Ramu","JAGAN","Steve","Swift"]
let namesArrayData = NSKeyedArchiver.archivedData(withRootObject: nameArray)
UserDefaults.standard.set(namesArrayData, forKey: "arrayData")
RetriveData
let retriveArrayData= UserDefaults.standard.object(forKey: "arrayData") as? NSData
if let retriveArrayData= namesArrayData{
let retriveArray = NSKeyedUnarchiver.unarchiveObject(with: namesArraydata as Data) as? [nameArray]
print(retriveArray )
}
This has been changed in swift 3.
Note that this works with device but not playground or simulator
//store the array
let array = ["horse", "cow", "camel", "sheep", "goat"]
let defaults = UserDefaults.standard
defaults.setValue(array, forKey: "history")
defaults.synchronize()
//Retrieve the array
if((UserDefaults.standard.array(forKey: "history")) != nil){
let historyWords = (UserDefaults.standard.array(forKey: "history") as? [String])!
print(historyWords)
}
Store into User Default:
let arrayFruit = ["Apple","Banana","Orange","Grapes","Watermelon"]
//store in user default
UserDefaults.standard.set(arrayFruit, forKey: "arrayFruit")
Retrieving array from User Defaults:
if let arr = UserDefaults.standard.array(forKey: "arrayFruit") as? [String]{
print(arr)
}
So I've been trying for a few hours for a way to store an array to NSUserDefault and print them to the cells but the data is not saving as an array, it basically only saves one value at a time.
var emailData = [String]()
var passwordData = [String]()
#IBAction func addPressed(sender: AnyObject) {
let defaults = NSUserDefaults.standardUserDefaults()
emailData.append(addEmail.text!)
passwordData.append(addPassword.text!)
var storedEmail = defaults.objectForKey("emailData") as? [String] ?? [String]()
var storedPasswords = defaults.objectForKey("passwordData") as? [String] ?? [String]()
// then update whats in the `NSUserDefault`
defaults.setObject(emailData, forKey: "emailData")
defaults.setObject(passwordData, forKey: "passwordData")
// call this after you update
defaults.synchronize() /*
NSUserDefaults.standardUserDefaults().setValue(addEmail.text, forKey: "email")
NSUserDefaults.standardUserDefaults().synchronize()
*/
}
So basically the data is not saving.
You can store Array too, by this way
let userDefault = NSUserDefaults.standardUserDefaults()
let arr = ["abc","xyz","pqr"]
userDefault.setObject(arr, forKey: "arr")
userDefault.synchronize()
let data = userDefault.objectForKey("arr") as! [String]
Save the Swift Array in Swift.
let kUserDefault = NSUserDefaults.standardUserDefaults()
kUserDefault.setObject(["KIRIT" , "MODI" , "FIRST" , "LAST"], forKey: "nameArray")
kUserDefault.synchronize()
Get Array
1. arrayForKey : You getting Swift Array
kUserDefault.arrayForKey("nameArray")!
2. objectForKey : You getting NSArray
kUserDefault.objectForKey("nameArray")!
3. valueForKey : You getting NSArray
kUserDefault.valueForKey("nameArray")
It is possible to store arrays in NSUserDefaults. But separating email and password in separate array is not suitable. You should store it as one object since they are related.
In your case an array of Dictionary objects is better, which is possible to store in NSUserDefaults as well, which you can retrieve as an array of Dictionary.
Here is the sample:
let userDefault = NSUserDefaults.standardUserDefaults()
var storedCredentials = userDefault.objectForKey("credentials") as? [[String:AnyObject]] ?? [[String:AnyObject]]()
let email =
[
"email" : addEmail.text!,
"password": addPassword.text!
]
storedCredentials.append(email)
userDefault.setObject(storedCredentials, forKey: "credentials")
userDefault.synchronize()
You can't save an array of [String] in NSUserDefault, if you look at the documentation :
For NSArray and NSDictionary objects, their contents must be property
list objects.
So what you can do is convert your [String] into NSData then save it into NSUserDefault.
// Store it as NSData
var emailData = [String]()
emailData.append("email1")
emailData.append("email2")
let emailIntoNSData = NSKeyedArchiver.archivedDataWithRootObject(emailData)
NSUserDefaults.standardUserDefaults().setObject(emailIntoNSData, forKey: "emailData")
// Retrieve it :
let emailFromNSData = NSUserDefaults.standardUserDefaults().objectForKey("emailData") as? NSData
if let emailFromNSData = emailFromNSData {
let emailArray = NSKeyedUnarchiver.unarchiveObjectWithData(emailFromNSData) as? [String]
if let emailArray = emailArray {
NSLog("Email Data : \(emailArray)") // ["email1","email2"]
// do something…
}
}
I am trying to store an array to NSUserDefaults and retrieve the array when needed to populate a UITableView.
Currently I am using:
//store data
NSUserDefaults.standardUserDefaults().setObject(myArray, forKey: "\(identity.text!)listA")
NSUserDefaults.standardUserDefaults().synchronize()
//retrieve data
let tabledata = NSUserDefaults.standardUserDefaults().stringForKey("\(identity.text!)listA")
myArray = [tabledata!]
tableView.reloadData()
But I get
fatal error: unexpectedly found nil while unwrapping an Optional
value
when trying to load the data. I am not sure if the issue is in the storage or the retrieval. Has anyone been through this before?
From your code I see you are storing some array
// Your code
NSUserDefaults.standardUserDefaults().setObject(myArray, forKey: "\(identity.text!)listA")
and retrieving a string
//Your code
let tabledata = NSUserDefaults.standardUserDefaults().stringForKey("\(identity.text!)listA")
There is probably a type mismatch, You store one type and retrieve another type.
While retrieving either use arrayForKey() or objectForKey() see the code below.
let tabledata = NSUserDefaults.standardUserDefaults().arrayForKey("\(identity.text!)listA")
or
let tabledata = NSUserDefaults.standardUserDefaults().objectForKey("\(identity.text!)listA")
If it is an array I would go with First one.
Here are the way that you can store and retrieved array of object with help of NSKeyArchive.
To Store array to NSUserDefault.
let placesData = NSKeyedArchiver.archivedData(withRootObject: placesArray)
UserDefaults.standard.set(placesData, forKey: "places")
To Retrieved array from NSUserDefault.
let placesData = UserDefaults.standard.object(forKey: "places") as? NSData
if let placesData = placesData {
let placesArray = NSKeyedUnarchiver.unarchiveObject(with: placesData as Data) as? [Place]
print(placesArray)
}
Hope this help you.
Saving and Retrieving a String array to UserDefaults
Save array
let array = ["horse", "cow", "camel", "sheep", "goat"]
let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedStringArray")
Retrieve array
let defaults = UserDefaults.standard
let array = defaults.object(forKey: "SavedStringArray") as? [String] ?? [String]()
See more at How to save user settings using NSUserDefaults
What are you storing in the array?
If it's objects it won't work, if It's just strings or numbers then it should be fine.
Next steps you take should be to turn on exception breakpoints and maybe println() everything you can so you can pinpoint the exact whereabouts of the problem.
As a shot in the dark I would suggest maybe (identity.text!) is coming out as nil
Also you should probably change it to this
if let tabledata: NSArray = NSUserDefaults.standardUserDefaults().stringForKey("\(identity.text!)listA"){
myArray = [tabledata!]
tableView.reloadData()
}
This will make the code not even try to run unless there is a value it can use
Latest swift3 version to store array of data into userdefaults and get that array of data using keys
let nameArray = ["Ramu","JAGAN","Steve","Swift"]
let namesArrayData = NSKeyedArchiver.archivedData(withRootObject: nameArray)
UserDefaults.standard.set(namesArrayData, forKey: "arrayData")
RetriveData
let retriveArrayData= UserDefaults.standard.object(forKey: "arrayData") as? NSData
if let retriveArrayData= namesArrayData{
let retriveArray = NSKeyedUnarchiver.unarchiveObject(with: namesArraydata as Data) as? [nameArray]
print(retriveArray )
}
This has been changed in swift 3.
Note that this works with device but not playground or simulator
//store the array
let array = ["horse", "cow", "camel", "sheep", "goat"]
let defaults = UserDefaults.standard
defaults.setValue(array, forKey: "history")
defaults.synchronize()
//Retrieve the array
if((UserDefaults.standard.array(forKey: "history")) != nil){
let historyWords = (UserDefaults.standard.array(forKey: "history") as? [String])!
print(historyWords)
}
Store into User Default:
let arrayFruit = ["Apple","Banana","Orange","Grapes","Watermelon"]
//store in user default
UserDefaults.standard.set(arrayFruit, forKey: "arrayFruit")
Retrieving array from User Defaults:
if let arr = UserDefaults.standard.array(forKey: "arrayFruit") as? [String]{
print(arr)
}
I am using the following code to set a value into NSUserDefaults using Swift. Here is my code:
let key = "ticker"
let currencyTickerData = [key:"USD"]
NSUserDefaults.standardUserDefaults().setObject(currencyTickerData, forKey: key)
NSUserDefaults.standardUserDefaults().synchronize()
let tickerVal : [NSString]? = (NSUserDefaults.standardUserDefaults().objectForKey(key)) as? [NSString]
print(tickerVal)
For some reason, tickerVal is nil. Why is this? As far as I can tell, it should return "USD."
NSUserDefaults uses NSDictionary instead of Swift's dictionary type. You can explicitly type tickerVal as an NSDictionary like so:
let key = "ticker"
let currencyTickerData: NSDictionary = [key:"USD"]
NSUserDefaults.standardUserDefaults().setObject(currencyTickerData, forKey: key)
NSUserDefaults.standardUserDefaults().synchronize()
let tickerVal = (NSUserDefaults.standardUserDefaults().objectForKey(key)) as NSDictionary
print("\(tickerVal)")
It is same code that will save you're date:
var myValue:NSString = "USD"
NSUserDefaults.standardUserDefaults().setObject(myValue, forKey:"ticker")
NSUserDefaults.standardUserDefaults().synchronize()
var myOutput: AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("ticker")
println(myOutput)