【问题标题】:Ionic 2 storage not working on iOSIonic 2 存储无法在 iOS 上运行
【发布时间】:2017-08-17 01:53:55
【问题描述】:

Ionic 2 存储无法在 ios 上运行,但在 Android 上运行。我正在使用这个import { Storage } from '@ionic/storage'; 在本地存储数据。

我做了这样的样本

import { Storage } from '@ionic/storage';

export class MyApp {
  constructor(private storage: Storage) { }

  setData() {
    // set a key/value
    storage.set('username', 'johndoe');
  }
  getData() {
    // get a key/value pair
    storage.get('username').then((val) => {
      alert('Your username is', val);
    });
  }
}

它在 Android 上完美运行。但是当我尝试在 iOS 上构建时,它不起作用。数据不显示。关于如何在 ionic 2 中存储持久数据的一些建议,它可以在 android 和 iOS 平台上完美运行。

【问题讨论】:

    标签: angular typescript ionic2 storage


    【解决方案1】:

    首先,我没有看到您的主模块定义,所以我将首先谈到这一点。在您的主应用程序模块中,您需要导入 IoinicStorageModule,然后您需要将其放入您的 imports 部分:

    imports:[IonicStorageModule.forRoot({'yourappname'})]
    

    其次,我没有看到您检查存储是否已准备好,您可能也应该这样做:

    this.storage.ready()
        .then(() => {
            this.storage.set(key, value);
        });
    

    最后,您的本地存储问题可以通过这个简单的服务轻松解决:

    import { Injectable } from '@angular/core';
    import { Storage } from '@ionic/storage';
    
    @Injectable()
    export class LocalStorageService {
        constructor(private storage: Storage){
        }
    
        public setValue(key: string, value: string): Promise<boolean> {
            return this.storage.ready()
                .then(() => {
                    return this.storage.set(key, value)
                        .catch(() => {
                            return null;
                    });
                });
            //TODO: Handle storage not being available
        }
    
        public getValue(key: string): Promise<string> {
            return this.storage.ready()
                .then(() => {
                    return this.storage.get(key)
                        .catch(() => {
                            return null;
                        });
                });
            //TODO: Handle storage not being available
        }
    }
    

    我每天都使用它。不要忘记围绕它进行一些单元测试。

    【讨论】:

    • 我已经有了“IoinicStorageModule”,所以我直奔主题。无论如何,谢谢你。我稍后会试试。该代码是否适用于iOS?你测试了吗?
    • 根据文档 (github.com/ionic-team/ionic-storage),它是跨平台的,并为每个平台选择最佳解决方案。我目前无法访问 iOS,但会在应用上架应用商店之前对其进行测试。
    • 非常有趣。您可能会向 Ionic 的人员提交错误请求,因为它应该这样做。知道它不适合你,我一定会在发布前彻底测试它。
    【解决方案2】:

    如果您要安装 SQLite 插件,那么您在 iOS 上也不会遇到任何问题。

    这是SQLite 插件。

    在原生应用上下文中运行时,存储将优先使用 SQLite,因为它是最稳定和广泛使用的基于文件的 数据库,并避免像 localstorage 这样的一些陷阱 和 IndexedDB,例如操作系统决定以低速清除此类数据 磁盘空间情况。

    【讨论】:

    • 好的,谢谢。我会试试的。但我想要@ionic/storage,因为它很容易使用,只是它不适用于ios。好伤心:(
    猜你喜欢
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 2019-02-24
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多