I want to get a swift dictionary from NSUserDefaults as the format that I've saved before. I've saved the dictionary as [String:String] format, but while I'm getting the dictionary with dictionaryForKey(key) method I got [String:AnyObject]?. How can I convert [String:AnyObject]? to [String:String] or how can I get the dictionary in right format?
Saving to NSUserDefaults
var tasks: Dictionary<String,String> = [:]
let defaults = NSUserDefaults.standardUserDefaults()
let key = "key"
defaults.setObject(tasks, forKey: key)
defaults.synchronize()
Getting from NSUserDefaults
let defaults = NSUserDefaults.standardUserDefaults()
let key = "ananZaa"
let incomingArray = defaults.dictionaryForKey(key)
If you've registered it with a default value so it never can be nil, just downcast it to the proper type
let defaults = NSUserDefaults.standardUserDefaults()
let key = "ananZaa"
let incomingDictionary = defaults.objectForKey(key) as! Dictionary<String,String>
Related
I am accessing user default value as:
let data = UserDefaults.standard.object(forKey: identifier)
when I see the value in data it is visible as:
https://i.stack.imgur.com/UOjI8.png
type of data is
po type(of: data)
Swift.Optional<Any> . //Output
How can I access pageNumber?
since data is a dictionary in order to have access to pageNumber you need to cast data as a Dictionary
guard let data = UserDefaults.standard.value(forKey: identifier) as? [String: Any] else { //fallback here if you need return }
let pageNumber = data["pageNumber"] as? Int ?? 0
Simply use dictionary(forKey:) method on UserDefaults instance to directly fetch a dictionary from UserDefaults.
The dictionary returned is of type [String:Any]?
if let dict = UserDefaults.standard.dictionary(forKey: identifier) {
let pageNumber = dict["pageNumber"] as? Int
}
Note: pageNumber is of type Int?. Unwrap it to use further.
Saving NSMutableArray with NSUserDefaults in Swift Returns Nil
setObject method removed my codes like that and not work. i try all set types still not work. Any idead ?
var banksAccount : NSMutableArray = []
for bankJson in (self.users?[0].Banks)! {
self.banksAccount.add(bankJson)
}
UserDefaults.standard.set(self.banksAccount, forKey: "myBanksAccounts")
UserDefaults.standard.synchronize()
For saving
let cacheArrayData = NSKeyedArchiver.archivedData(withRootObject: banksAccount)
UserDefaults.standard.set(cacheArrayData, forKey: "EventItems")
For retrieving
let retriveArrayData = UserDefaults.standard.object(forKey: "EventItems") as? NSData
let retriveArray = NSKeyedUnarchiver.unarchiveObject(with: retriveArrayData! as Data) as? NSArray
self.eventsArray = NSMutableArray(array:retriveArray!)
I want to know how to remove both key and value in NSUserDefaults . removeobjectforkey only removes the value ?
removeObjectForKey(string)
Swift 3
to add value in NSUserDefault
integer
UserDefaults.standard.integer(forKey: "key")
a dictionary
UserDefaults.standard.set(Dictvariable, forKey: "key")
get value
from integer
key value = UserDefaults.standard.integer(forKey: "key")
get value from dictionary
let result = UserDefaults.standard.value(forKey: "key") as? [String: String] ?? [String: String]()
to remove(i not tried this u can try this take it from stackoverflow 99% its work)
UserDefaults.standard.removeObject(forKey: "yourKey")
I am using Swift and have a Set type that contains Int:
var setA : Set<Int>
How to save/load this Set type by using NSUserDefaults?
Convert the Set to Array which can be saved in NSUserDefaults
let arrayA = Array(setA)
NSUserDefaults.standardUserDefaults().setObject(arrayA, forKey:"mySet")
and get the array and convert it back to Set
let arrayA = NSUserDefaults.standardUserDefaults().objectForKey("mySet") as! [Int]
let setA = Set(arrayA)
If you register the key/value pair as Apple recommends
let defaults = NSUserDefaults.standardUserDefaults()
let defaultValues = ["mySet" : [Int]()]
defaults.registerDefaults(defaultValues)
the value is never nil and can be safely unwrapped.
I need a way to save key and value pairs in swift for my application. I am new to IOS programming, but I know Android and I am looking for something like shared preferences in android, but for swift. By "save," I mean that when the user quits out of the application, the key and value pairs are saved in the local data.
Swift 3.0
Saving Data:
let userDefaults = UserDefaults.standard
userDefaults.set(yourKey, forKey: "yourKey")
userDefaults.synchronize()
Reading Data:
if let yourVariable: AnyObject = UserDefaults.standard.object(forKey: "yourKey") as AnyObject? { }
What you are looking for is called "Userdefaults" - you can use them like this:
Saving Data:
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(variable, forKey: "yourKey")
userDefaults.synchronize()
Reading Data:
if let yourVariable: AnyObject = NSUserDefaults.standardUserDefaults().objectForKey("yourKey") {
....
Here you find more information:
https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/index.html
Working way for Swift 3+:
// Storing values
UserDefaults.standard.set(true, forKey: "KeyName") // Bool
UserDefaults.standard.set(1, forKey: "KeyName") // Integer
UserDefaults.standard.set("TEST", forKey: "KeyName") // setObject
// Retrieving values
UserDefaults.standard.bool(forKey: "KeyName")
UserDefaults.standard.integer(forKey: "KeyName")
UserDefaults.standard.string(forKey: "KeyName")
// Removing values
UserDefaults.standard.removeObject(forKey: "KeyName")