Xamarin Forms:是否可以使用 SettingsPlugin 保存和检索 EpubBook 数据?

Xamarin Forms: Is it possible to save and retrieve an EpubBook data using SettingsPlugin?

我正在使用 SettingsPlugin 将值保存到本地数据库。使用这个插件,我保存了一个 EpubBook 数据,如下所示:

CrossSettings.Current.AddOrUpdateValue("epub", epubBook.ToString());

检索到如下值:

string epubString = CrossSettings.Current.GetValueOrDefault("epub", string.Empty);
if (!string.IsNullOrWhiteSpace(epubString))
{
    //Need to convert string epub data to EpubBook data
}

我需要将字符串 epub 数据转换为 EpubBook?这可能吗?这是为了缓存 EpubBook 数据。

我用 Application.Current.Properties 做了同样的事情,保存和检索在那里工作正常。请看下面的代码:

//Saving value
Application.Current.Properties["epub"] = epubBook;
//Retriving value
EpubBook epubBook = (EpubBook)Application.Current.Properties["epub"];

但是 Application.Current.Properties 值会在关闭应用程序后自动清除。这就是我开始研究 SettingsPlugin 的原因。那么有什么方法可以使用 SettingsPlugin 来保存和检索 EpubBook 吗?如果没有建议缓存 EpubBook 数据的方法?

来自我 XF thread 的回答。

尝试使用http客户端请求数据,以便我们可以直接获取字节:

bool hasKey = Preferences.ContainsKey("epub");
if (hasKey)
{
    string fileName = Preferences.Get("epub", string.Empty);
    var folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    var filePath = Path.Combine(folderPath, fileName);
    var bytes = File.ReadAllBytes(filePath);
    // convert
    var stream1 = new MemoryStream(bytes);
    epubBook = EpubReader.ReadBook(stream1);
}
else
{
    Stream stream;
    //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fileUrl);
    //HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    HttpClient client = new HttpClient();
    var response = await client.GetAsync(fileUrl);

    //stream = response.GetResponseStream();
    stream = await response.Content.ReadAsStreamAsync();
    epubBook = EpubReader.ReadBook(stream);

    //saving to folder
    byte[] bytes = await response.Content.ReadAsByteArrayAsync();
    string filename = Path.GetFileName(fileUrl);
    var folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    var filePath = Path.Combine(folderPath, filename);
    File.WriteAllBytes(filePath, bytes);
    Preferences.Set("epub", filename);           
}

我们需要在 Android 上添加明文:

<application android:label="EPubDemo.Android" android:usesCleartextTraffic="true"></application>

并在 iOS 中禁用 ATS 此请求是 http。

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSAllowsArbitraryLoads</key>
  <true/>
</dict>