Forum Xamarin Xamarin.iOS

What is the best way to store or to cache a data?

koby1koby1 Member ✭✭

Hi, I was trying to access a GET method from an API. I successfully fetched the data but my problem now is I wanted to pass the data I got to another UIView. I tried using akavache but I had a hard time using it



  • LandLuLandLu Member, Xamarin Team Xamurai

    You can save it to your app's sandbox document folder directly:

    var docPath = NSSearchPath.GetDirectories(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User).FirstOrDefault();
    var filePath = Path.Combine(docPath, "MyData.arch");
    data.Save(filePath, true);
    // Retrieve code
    NSData myData = NSData.FromFile(filePath);

    This will persist the data even though your app has been quit, the data will not be lost.
    Or you can try to use NSKeyedArchiver to encode your data to the file path:

    NSKeyedArchiver.ArchiveRootObjectToFile(data, filePath);
    // Retrieve
    var data = (NSData)NSKeyedUnarchiver.UnarchiveFile(filePath);

    Moreover if the second UIView can be reached, you can pass this data as parameter directly:

    var secondView = new CustomView(); = data;

    In this way, the data will be lost when app is force quit.

Sign In or Register to comment.