SharedPreferences allow us to store something in the sharedPreferences memory of the device. You could map the stored value with a key. Once you store something in the sharedPreferences using a key, then you could retrieve the value using the same key. Also you could change the stored value if it is necessary. Nowadays most of the applications make use of sharedPreferences to store the app setting and etc.. In this tutorial you're gonna learn how to use sharedPreferences to store and retrieve value in your ios app using swift language.
*Copy and paste the below code to your swift class file
>The Below code saves the value India for the key MyCountry.
>The Below code retrieves the value of the key MyCountry.
And it will store the data if it does not exists.
*Copy and paste the below code to your swift class file
>The Below code saves the value India for the key MyCountry.
func storeData(){
let sharedPref= NSUserDefaults.standardUserDefaults()
sharedPref.setValue("India", forKey: "MyCountry")
}
>The Below code retrieves the value of the key MyCountry.
And it will store the data if it does not exists.
func retrieveData(){
let sharedPref = NSUserDefaults.standardUserDefaults()
if let country = prefs.stringForKey("MyCountry"){
println("The MyCountry has a Country defined: " + country)
}else{
//Nothing stored in NSUserDefaults yet. Set a value.
sharedPref.setValue("India", forKey: "MyCountry")
}
}
No comments:
Post a Comment