Pages

Sunday, 27 January 2019

User Defaults in Xamarin.IOS

IOS provides many ways of storing data of an application. One of this way is called NSUserDefaults. NSUserDefaults allow you to save and retrieve data in the form of key, value pair.

NSUserDefaults class provides its own built in mechanisms to save float, double, integers, Boolean and URL data. To save a custom object it should be converted to NSData object using NSUserDefaults.
Storing
    NSUserDefaults.StandardUserDefaults.SetString("value", "key");

Example1:

       NSUserDefaults values = new NSUserDefaults();  

// Store value on Userdefaults  
values .SetString(txtString.Text, "stringvalue");  

values .SetInt(Int32.Parse(txtInteger.Text), "integervalue");  

// Get values form Userdefaults  

lblString.Text = values .StringForKey("stringvalue");  
lblInteger.Text = values .IntForKey("integervalue").ToString();  
lblBoolean.Text = values .BoolForKey("swithvalue").ToString();  



    NSUserDefaults.StandardUserDefaults.Synchronize();
Retrieve

NSUserDefaults.StandardUserDefaults.StringForKey("key");
Clear:

NSUserDefaults.StandardUserDefaults.RemoveObject("key");



Example 2: 

public partial class ViewController : UIViewController  
{  
public static string UserNameKey = "user_name";  

protected ViewController(IntPtr handle) : base(handle)  
{  
// Note: this .ctor should not contain any initialization logic.  
}  

public override void ViewDidLoad()  
{  
base.ViewDidLoad();  
  
SaveUserName(UserNameKey, "Subramanyam");  
 
var readUserName = ReadUserName();  
}  

public override void DidReceiveMemoryWarning()  
{  
base.DidReceiveMemoryWarning();  
// Release any cached data, images, etc that aren't in use.  
}  

void SaveUserName(string key, string value){  
var plist = NSUserDefaults.StandardUserDefaults;  
plist.SetString(value, key);   
plist.Synchronize();  
}  

string ReadUserName( )  
{  
return NSUserDefaults.StandardUserDefaults.StringForKey(UserNameKey);  
}  

No comments:

Post a Comment