在Xamarin.Android/Xamarin.iOS中使用Akavache

jok*_*ane 3 c# xamarin.ios xamarin.android xamarin

我已成功让Akavache为Windows桌面,.NET 4.5 WPF项目工作,但当我尝试为Xamarin(iOS和Android)目标构建它时,BlobCache单例未正确初始化.BlobCache.Secure一片空白.(我已经尝试了SQLite和'vanilla'构建)

老实说,我发现Akavache的示例/文档有点薄.我不是Reactive的用户,我发现很多Paul的代码非常不透明.

我只是想为跨平台应用程序做一些非常简单,安全的app状态缓存.

// where we store the user's application state
BlobCache.ApplicationName = "myApp";
BlobCache.EnsureInitialized();

public AppState State
{
    get
    {
        return _appState;
    }
    set
    {
        _appState = value;
    }
}

public void Load()
{
    try
    {
        State = BlobCache.Secure.GetObjectAsync<AppState>.FirstOrDefault();
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.ToString());
        State = new AppState();
    }           
}

public void Save()
{
    try
    {           
        BlobCache.Secure.InsertObject("AppState", State);
    }
    catch(Exception ex)
    {
        Debug.WriteLine(ex.ToString());
    }
}
Run Code Online (Sandbox Code Playgroud)

Ana*_*tts 8

所以,你现在必须在Xamarin上做一些愚蠢的伎俩,我最近才知道.我要将这些添加到文档中(或者在Android案例中,只修复bug)

Xamarin.iOS

在iOS上,Type.GetType()不会加载程序集,这与任何其他平台不同.所以,你必须在你的AppDelegate中运行这个愚蠢的鹅代码:

var r = new ModernDependencyResolver();
(new ReactiveUI.Registrations()).Register((f,t) => r.Register(f, t));
(new ReactiveUI.Cocoa.Registrations()).Register((f,t) => r.Register(f, t));
(new ReactiveUI.Mobile.Registrations()).Register((f,t) => r.Register(f, t));

RxApp.DependencyResolver = r;
(new Akavache.Registrations()).Register(r.Register);
(new Akavache.Mobile.Registrations()).Register(r.Register);
(new Akavache.Sqlite3.Registrations()).Register(r.Register);
Run Code Online (Sandbox Code Playgroud)

通常,此代码运行AutoMagically™.

Xamarin.Android

注册在Xamarin.Android上运行正常,但由于我怀疑是Akavache中的错误,您可能需要注册AutoSuspend(即使您不使用它).

  1. 在你的所有活动中,申报 AutoSuspendActivityHelper autoSuspendHelper;
  2. 在构造函数中,添加:

    autoSuspendHelper = new AutoSuspendActivityHelper(this);
    autoSuspendHelper.OnCreate(bundle);
    
    Run Code Online (Sandbox Code Playgroud)
  3. 覆盖OnPause,OnResume和,OnSaveInstanceState并调用适当的autoSuspendHelper方法,即:

    autoSuspendHelper.OnPause();
    
    Run Code Online (Sandbox Code Playgroud)

更麻烦?

请通过发送电子邮件至paul@github.com或在github/akavache提交问题告诉我.我已经发布了一个可以在iOS和Android上运行的Akavache的生产应用程序,它确实有效,但我意识到可能有点Tricky™可以让它工作.