Angularjs localStorage存储cordova应用程序中的设置

num*_*web 5 settings local-storage angularjs cordova

我正在使用AngularJS v1.2.7和Cordova 3.3.0(Android)我需要在手机内存中存储一​​些设置 - 所以当应用程序/设备重新启动时,应用程序仍然可以访问这些存储的数据.

关于这个的任何教程?我找不到任何:(

知道Cordova支持; LocalStorage,WebSQL(不再维护),IndexedDB(Opera和Safari 没有广泛支持).我倾向于使用LocalStorage,但是即使在我重启设备后它仍保留/记住数据?

目前我正在使用Richard Szalay的答案#12969480.

Pet*_*ete 1

我建议编写一个自定义插件并将设置正确存储在 Objective-C 用户默认值中。

LocalStorage 不是永久存储,WebSQL 对于存储设置来说似乎有点矫枉过正。

您不必过多参与 Objective-C,并且有很好的 Phonegap/Cordova 插件指南:

http://docs.phonegap.com/en/3.3.0/guide_hybrid_plugins_index.md.html#Plugin%20Development%20Guide

我使用此代码来存储“FirstRun”变量来检查应用程序是否是新安装的。该插件检查应用程序之前是否运行过,并返回 1 或 0,该值被解析为整数并评估为 true/false。

您可以更新此代码并向“AppChecks”类添加更多方法。我把所有简单的检查和设置存储都放在这个类中。

应用程序检查.h

#import <Cordova/CDVPlugin.h>

@interface AppChecks : CDVPlugin

- (void) checkFirstRun:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;

@end
Run Code Online (Sandbox Code Playgroud)

应用检查.m

#import "AppChecks.h"
#import <Cordova/CDVPluginResult.h>

@implementation AppChecks

- (void) checkFirstRun:(NSMutableArray *)arguments withDict:(NSMutableDictionary *)options {
NSString* callbackId = [arguments objectAtIndex:0];

CDVPluginResult* pluginResult = nil;
NSString* javaScript = nil;

@try {

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *isFirstRun = @"1";

    if (![defaults objectForKey:@"firstRun"]) {
        [defaults setObject:[NSDate date] forKey:@"firstRun"];
    } else {
        isFirstRun = @"0";
    }

    pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:isFirstRun];
    javaScript = [pluginResult toSuccessCallbackString:callbackId];
} @catch (NSException* exception) {
    // could not get locale
    pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_JSON_EXCEPTION messageAsString:[exception reason]];
    javaScript = [pluginResult toErrorCallbackString:callbackId];
}
[self writeJavascript:javaScript];
}
@end
Run Code Online (Sandbox Code Playgroud)

在我的 Javascript 代码中使用:

cordova.exec(
    function( isFirstRun ) {
        isFirstRun = parseInt( isFirstRun );
        if( isFirstRun ) {
          // do stuff for first run
        }
    },
    function(err) {
        // handle error from plugin
    },
    "AppChecks",
    "checkFirstRun",
    []
);
Run Code Online (Sandbox Code Playgroud)

  • 我的经验仅适用于 Cordova 2.x 和 Android,但 localStorage_was_ 在重新启动之间仍然存在(尽管在重新安装之间并非如此)。 (2认同)