iosxamarin.iosnsuserdefaultsshare-extension

Add a Class with byte[] to NSUserDefaults in iOS Share Extension (Xamarin)


In Xamarin.iOS Share Extension, I'd like to store my selected files (like pdf, images, word etc.) in my NSUserDefaults and when the main application starts, I'll have access to the files stored in it.

Here is my file class :

public class MyClass {    
    public string FileName { get; set; }
    public byte[] Content { get; set; } 
}

So in LoadItem in DidSelectPost methods, I create by object by using byte[] of files. Then for saving datas in NSUserDefaults, I convert my object to JSON like this (by using Newtonsoft.Json library):

string jsonString = JsonConvert.SerializeObject(myFileObject);

and I set it to NSUserDefaults object like that:

NSUser.SetValueForKey(new NSString(myFileObject), new NSString("FileSharing" + count));

or

NSUser.SetValueForKey(new NSString(myFileObject), new NSString("FileSharing"+ count));

And after I'll synchronise my items : NSUser.Synchronize());

Everything goes well, but when the main application open, the new data is not here.

string toDesralize = nSUser.StringForKey("FileSharing0");

I've tried for many files, and I've found out that this issue works only for files with low height and it doesn't work for files like 14mb. How can i save files with high height in NSUserDefaults? Is there any other way for doing the same job ?


Solution

  • You can use file system to store and read data in Xamarin.iOS:

        var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        var filename = Path.Combine(documents, "Write.txt");
        //save text
        File.WriteAllText(filename, "Write this text into a file");
        //save bytes
        File.WriteAllBytes(filename,yourBytes);
    

    And the read methods:

        var text = File.ReadAllText("TestData/ReadMe.txt");
        Console.WriteLine(text);
        var bytes = File.ReadAllBytes("path");