0

I made this post earlier about storing a list with the App class: List does not get saved when I use Application.Current.SavePropertiesAsync in Xamarin forms

And it turned out it was possible to do it with a json-implementation. However I now face another task which is to store an ImageSource locally.

With my current code where I try to store a ImageSource locally with the App class it does not get saved when I restart the app.

var setImage = new PhotoResultEventArgs(App.imageData, App.imageWidth, App.imageHeight);

photo.Source = ImageSource.FromStream(() => new MemoryStream(setImage.Image));
Application.Current.Properties["photo"] = photo.Source;
await Application.Current.SavePropertiesAsync();

It returns null when I restart the app:

if (Application.Current.Properties.ContainsKey("photo"))
{
   //i dont reach this code
}

Is there anyway to store an ImageSource with the App class by converting it somehow or do I have to look for an another solution? If so I would appreciate any links, tips I can get.

Community
  • 1
  • 1
Carlos Rodrigez
  • 1,347
  • 1
  • 15
  • 32

1 Answers1

0

The properties dictionary can only contain primitive values as noted on this page.

Note: the Properties dictionary can only serialize primitive types for storage. Attempting to store other types (such as List can fail silently.

That is probably what is happening to you right now. What you probably want is to save the image somewhere and save the path to it. To do this in a Xamarin.Forms manner, you need to use the DependencyService.

Define an interface in your shared code, something like this:

public interface IFileService
{
    string SaveFile(Stream s);
}

And implement this interface in each platform that you want to support. For instance on iOS;

[assembly: Xamarin.Forms.Dependency (typeof (FileService_iOS))]
namespace MyApp
{
    public class FileService_iOS : IFileService
    {
        string SaveFile(Stream s)
        {
            // Implement here and return the path to the saved file
        }
    }
}

You can now save it by implementing code like this

Application.Current.Properties["photoPath"] = DependencyService.Get<IFileService>()?.SaveFile(myStream);

Gerald Versluis
  • 30,492
  • 6
  • 73
  • 100