UserDefaults swift as array check if value exists - ios

So I'm using:
var defaults = UserDefaults.standard
....
seenPosts.insert(CellsData[indexPath.row]["id"] as! Int, at: 0)
So I'm basically using UserDefaults to set an array with ids, now I want to check if that array has a value
if (self.defaults.data(forKey: "seen_posts").contains(5){
//do action
}
But doesn't work, any tips on how you can check UserDefaults array if it has a specific value in the array?

Use array(forKey. data(forKey is for (NS)Data objects.
You can check for nil and if the array contains the value in one expression:
let defaults = UserDefaults.standard
if let seenPosts = defaults.array(forKey: "seen_posts") as? [Int], !seenPosts.contains(5) {
seenPosts.insert(CellsData[indexPath.row]["id"] as! Int, at: 0)
}

Related

Removing a single key value of UserDefaults in Swift 3

I am tracking a user's preferences in my iOS app using UserDefaults -- when a user selects a table cell, it adds the cell's text to my key. That part works.
Now, I want to allow the user to remove the matching key value from the key when a row is selected. If a cell says "Episode 1", it should remove the value from UserDefaults.
From the documentation, there's an instance method for removeObject. Here's what I wrote:
let defaults = UserDefaults.standard
var myarray = defaults.stringArray(forKey: "SavedStringArray") ?? [String]()
if let datastring = TableData[indexPath.row] as? String {
if !myarray.contains(datastring) {
myarray.append(datastring)
defaults.removeObject(myarray, forKey: "SavedStringArray")
defaults.synchronize()
}
This returns an error for Extra argument in call -- I assume it means myarray, but if I can't add that argument, how can I tell it to remove only one value (stored in myarray)?
If I print the UserDefaults.standard, it will return a list of stored episode values like `["First Episode", "Second Episode", "Third Episode"]
Any idea how I can remove Third Episode when that cell is clicked here?
I have following code which will work for you.
if myarray.contains(datastring) {
myarray.remove(at: myarray.index(of: datastring)!)
} else {
myarray.append(datastring)
}
defaults.set(myarray, forKey: "SavedStringArray")
This code will remove element from array and set array again in User defaults for same key, So it will replace you array with new array.
You can add if string is not present or remove the string if it is present. And then update the array.
Then set that array for the key.
if !myarray.contains(datastring) {
myarray.append(datastring)
} else {
myarray = myarray.filter{$0 != datastring}
}
defaults.set(myarray, forKey: "SavedStringArray")
You can try This logic for array of type String i.e. [String]
var arrStr:[String] = ["Cat","Rat","Mouse"]
print(arrStr)
let datastring = "Rat"
if !arrStr.contains(datastring) {
arrStr.append(datastring)
} else {
arrStr.remove(at: arrStr.index(of: datastring)!)
}
print(arrStr)
UserDefaults.standard.set(arrStr, forKey: "SavedStringArray")
UserDefaults.standard.synchronize()

Extract vaues from an array in swift

I'm getting values of string in my response to whom i'm storing in an array. Its is storing properly.Now i want to get that values out of my array because later i have to add that in an another string to get their sum. My array looks like this, [0.5,0.5,0.5]. I have to extract all the 0.5 values and add them. I have tried a code it extract the values but in result it shows 0 value. My code is this,
let itemprice = UserDefaults.standard.string(forKey: "itemPrice")
print(itemprice)
let defaults = UserDefaults.standard
let array = defaults.array(forKey: "addonPrice") as? [Int] ?? [Int]()
print(array)
let resultant = array.reduce(0, +)
print(resultant)
let result = itemprice! + String(resultant)
print(result)
i'm trying to add the arrays value to another value with the name itemprice. How can i get out all the values from my array and add them. The values in the array varies different time.
You are getting 0 as a result of let resultant = array.reduce(0, +) because in
let array = defaults.array(forKey: "addonPrice") as? [Int] ?? [Int]()
either the value stored in the defaults is an empty array, or the cast as? [Int] fails.
Considering you claim that the array is supposed to hold values [0.5,0.5,0.5] I assume that it is the latter case. [0.5,0.5,0.5] is an array of Double values, not Int values.
Try to fix it this way:
let array = defaults.array(forKey: "addonPrice") as? [Double] ?? [Double]()
UPDATE
From comments it seems that you are using strings everywhere, so then:
let itemprice = UserDefaults.standard.string(forKey: "itemPrice")
print(itemprice)
let defaults = UserDefaults.standard
// take it as an array of strings
let array = defaults.array(forKey: "addonPrice") as? [String] ?? [String]()
print(array)
// convert strings to Double
let resultant = array.map { Double($0)! }.reduce(0, +)
print(resultant)
let result = Double(itemprice!)! + resultant
print(result)
Although I would strongly recommend you to work with Double from the beginning (both to store it and use it).

How to save and retrieve Array of Objects value from Dictionary in Swift iOS?

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

How to for loop in userDefaults swift

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")

User defaults gives nil value in Swift 3.0

I am new to swift and trying to store NSMutableArray in Userdefaults. Here is what I am doinig :
//to save aaray in user defaults
var set:NSMutableArray = NSMutableArray(objects: self.listId)
self.saveListIdArray(set)
func saveListIdArray(_ params: NSMutableArray = []) {
let defaults = UserDefaults.standard
defaults.set(params, forKey: "ArrayKey")
defaults.synchronize()
}
//to get array from user default
func getUserDefaultKeyForAllObject(key userDefaultsKey: String) -> NSMutableArray {
let array = UserDefaults.standard.object(forKey: NSUserDefaultsKey.LIST_ID_ARRAY) as! NSMutableArray
print(array)
return array
}
App crashes with "fatal error: unexpectedly found nil while unwrapping an Optional value" exception.
Ignore the way I ask the question, help me out here.
Thank you.
Try converting to NSData then storing to nsuserdefaults like below
func saveListIdArray(_ params: NSMutableArray = []) {
let data = NSKeyedArchiver.archivedData(withRootObject: params)
UserDefaults.standard.set(data, forKey: "test")
UserDefaults.standard.synchronize()
}
For retrieving the data use
if let data = UserDefaults.standard.object(forKey: "test") as? Data {
if let storedData = NSKeyedUnarchiver.unarchiveObject(with: data) as? NSMutableArray
{
// In here you can access your array
}
}
You are force unwrapping the NSMutableArray for a key. Don't force unwrap when you try to get the value from a dictionary or UserDefault for a key because there may be a chance that the value does not exist for that key and force unwrapping will crash your app.
Do this as:
//to get array from user default
if let array = UserDefaults.standard.object(forKey:"ArrayKey") as? NSMutableArray
print(array)
}
I have 2 possible reasons for this:
You need to be 100% sure that you are retrieving array with the same key as you save it with. In your code you are saving the array with "ArrayKey" but retrieving it with NSUserDefaultsKey.LIST_ID_ARRAY, are you sure this is the same string?
What datatype is self.listId? If it's a custom class then you need to make that class conform to the nscoding protocol, then encode it to Data and save that to the userDefaults (Save custom objects into NSUserDefaults)
A 3rd reason is that you are trying to get an object from the defaults without ever writing anything to it. Try changing
let array = UserDefaults.standard.object(forKey: NSUserDefaultsKey.LIST_ID_ARRAY) as! NSMutableArray
print(array)
return array
to
if let array = UserDefaults.standard.object(forKey: "ArrayKey") as? NSMutableArray {
print(array)
return array
}
else {
return NSMutableArray()
}

Resources