我建议编写一个自定义插件并将设置正确存储在 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,将其解析为整数并评估为真/假。
您可以更新此代码并向“AppChecks”类添加更多方法。我把所有简单的检查和设置存储都放在这个类中。
AppChecks.h
#import <Cordova/CDVPlugin.h>
@interface AppChecks : CDVPlugin
- (void) checkFirstRun:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
@end
AppChecks.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
在我的 Javascript 代码中使用:
cordova.exec(
function( isFirstRun ) {
isFirstRun = parseInt( isFirstRun );
if( isFirstRun ) {
// do stuff for first run
}
},
function(err) {
// handle error from plugin
},
"AppChecks",
"checkFirstRun",
[]
);