This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I display the application version revision in my application's settings bundle?
I have an iPhone application that displays the current version as a Settings constant (just like Skype does).
When I released the first version of the application, I use this code to set the app Settings:
- (void)registerDefaultsFromSettingsBundle {
NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:#"Settings" ofType:#"bundle"];
if(!settingsBundle) {
NSLog(#"Could not find Settings.bundle");
return;
}
NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:#"Root.plist"]];
NSArray *preferences = [settings objectForKey:#"PreferenceSpecifiers"];
NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]];
for(NSDictionary *prefSpecification in preferences) {
NSString *key = [prefSpecification objectForKey:#"Key"];
if(key) {
[defaultsToRegister setObject:[prefSpecification objectForKey:#"DefaultValue"] forKey:key];
}
}
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister];
[defaultsToRegister release];
}
And this worked fine and dandy.
The problem I face now is that if you update the application, these defaults (Settings) are nor re-written, so the application version is not updated.
How can I force that an specific Settings is set on every install?
Thanks
Gonso
You can use the following 'Run Script' Build Phase:
CFBundleShortVersionString=`/usr/libexec/PlistBuddy -c "Print :CFBundleShortVersionString" ${SRCROOT}/YourApp/YourApp-Info.plist`
CFBundleVersion=`/usr/libexec/PlistBuddy -c "Print :CFBundleVersion" ${SRCROOT}/YourApp/YourApp-Info.plist`
/usr/libexec/PlistBuddy -c "Set :PreferenceSpecifiers:3:DefaultValue '${CFBundleShortVersionString} (${CFBundleVersion})'" ${SRCROOT}/YourApp/Settings.bundle/Root.plist
All you need to do, is to replace YourApp with your app's name and set the appropriate keypath.
In my case, I have 4 items in the PreferenceSpecifiers array, and I need to set the value for the last item from the array and that's why I used ':PreferenceSpecifiers:3:DefaultValue'
I have this code in my application delegate's -applicationDidFinishLaunching:
#if DDEBUG // debugging/testing
NSString *versionString = [NSString stringWithFormat:#"v%#",[[NSBundle mainBundle] objectForInfoDictionaryKey:#"CFBundleVersion"]];
#else
NSString *versionString = [NSString stringWithFormat:#"Version %#",[[NSBundle mainBundle] objectForInfoDictionaryKey:#"CFBundleShortVersionString"]];
#endif // DDEBUG
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:versionString forKey:#"version"];
printf("Version: = %s\n", [versionString cStringUsingEncoding:NSMacOSRomanStringEncoding]);
[defaults synchronize]; // force immediate saving of defaults.
But app has to be run before Settings 'version' updates to reflect the change.
Why wouldn't you set the version number from the mainBundle?
NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:#"CFBundleVersion"]];
This way you don't have to update the settings file for every version. If you want to compare existing versus new install version. You could write out the version number to a file on launch and compare the directory version with the launch version.
Related
Hi everybody I have an issue in my app. I need to determine if my app has has been updated to some point. I found out with this method how I can get the current version
NSString *first = [[[NSBundle mainBundle] infoDictionary] objectForKey:#"CFBundleShortVersionString"];
NSString *second = [[[NSBundle mainBundle] infoDictionary] objectForKey:#"CFBundleVersion"];
If the app is updated from itunes, Who var is changed to determine my app has been updated because I prove by modification from xcode in the Targets>Summary>Version to prove .The first var changes but the second does not change.
What I have to select the first or the second, and how I can prove this?
I'm not sure if this is what you are looking for but this code can tell you if your app has been updated by storing version information in NSUserDefaults.
- (BOOL)wasUpdated {
// access NSUserDefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// get previous version number from defaults
NSString *previousVersion = [defaults stringForKey:#"previousVersion"];
// get current version number from info plist
NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:#"CFBundleVersion"];
// check against previousVersion being nil
if (!previousVersion) {
// set current version to previous version
[defaults setObject:currentVersion forKey:#"previousVersion"];
// previousVersion didn't exist and can't be checked, return NO
return NO;
}
// return YES if the versions are not the same
if (NSOrderedSame != [previousVersion compare:currentVersion]) return YES;
// return NO if they are the same
return NO;
}
Hopefully that's what you needed. Tell me if I didn't understand what you meant.
I have an app with version 1.0 on app store which uses sqlite database for reading the data.Now I want to update my version to 1.1 with update in database file.While using developer certificate when I install app on device it did not update the database as the database file already exist in documents folder so i have to manually delete the app and install it again.My question is, when any user update the app, will the database also get updated according the current version.Any suggestions are welcome.Thanks
I am sure there are many ways to do this (and many ways better then mine as well), but the way that I handle such problems is as follows:
First I define a constant in the first .h file of the app (the one that will load first) to indicate First Time load and set it to 0:
#define FirstTime 0
Now you have to know that I have the intention to save the value of this constant in the Documents folder for future references, therefore I use a Shared Data Instance. In the viewDidLoad I do the following test:
//if first time run of this version
if( [MyDataModel sharedInstance].count < (FirstTime + 1) )
{
//do what you need to do as the first time load for this version
[MyDataModel sharedInstance].count++
//save the count value to disk so on next run you are not first time
//this means count = 1
}
Now the trick is on your new app version (say 1.1). I change the FirstTime to 2:
#define FirstTime 2
Since the saved First Time value on disc is 1 this means you will be caught by the if statement above, therefore inside it you can do anything you want like delete the old tables and recreate them again with the new formation.
Again not that brilliant, but solves the case!
This approach relies on NSUserDefaults. The idea is to get the previous app version number(if exists) from NSUserDefaults and compare it with the current version.
The code performs db upgrade if the previous app version < than current version or if the previous version is nil. It means that this approach can be used even though the app was already published on the AppStore. It will upgrade database to the new version during the app update.
This is a plist file:
There is an array which is composed of the version number and a set of sql queries for the corresponding upgrade version.
Suppose that a previous version is 1.2 and the actual version is 1.4 the code perform the upgrade only from the version 1.2 to 1.4. If the previous version is 1.3 and the current 1.4 the code performs upgrade only from 1.3 to 1.4.
If the previous version is nil the code performs upgrade to 1.1 then to 1.2 then to 1.3 and finally to 1.4.
NSString * const VERSION_KEY = #"version";
-(void)upgradeDatabaseIfRequired{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *previousVersion=[defaults objectForKey:VERSION_KEY];
NSString *currentVersion=[self versionNumberString];
if (previousVersion==nil || [previousVersion compare: currentVersion options: NSNumericSearch] == NSOrderedAscending) {
// previous < current
//read upgrade sqls from file
NSString *plistPath = [[NSBundle mainBundle] pathForResource:#"UpgradeDatabase" ofType:#"plist"];
NSArray *plist = [NSArray arrayWithContentsOfFile:plistPath];
if (previousVersion==nil) {//perform all upgrades
for (NSDictionary *dictionary in plist) {
NSString *version=[dictionary objectForKey:#"version"];
NSLog(#"Upgrading to v. %#", version);
NSArray *sqlQueries=[dictionary objectForKey:#"sql"];
while (![DB executeMultipleSql:sqlQueries]) {
NSLog(#"Failed to upgrade database to v. %#, Retrying...", version);
};
}
}else{
for (NSDictionary *dictionary in plist) {
NSString *version=[dictionary objectForKey:#"version"];
if ([previousVersion compare: version options: NSNumericSearch] == NSOrderedAscending) {
//previous < version
NSLog(#"Upgrading to v. %#", version);
NSArray *sqlQueries=[dictionary objectForKey:#"sql"];
while (![DB executeMultipleSql:sqlQueries]) {
NSLog(#"Failed to upgrade database to v. %#, Retrying...", version);
};
}
}
}
[defaults setObject:currentVersion forKey:VERSION_KEY];
[defaults synchronize];
}
}
- (NSString *)versionNumberString {
NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
NSString *majorVersion = [infoDictionary objectForKey:#"CFBundleShortVersionString"];
return majorVersion;
}
You can use .plist as well:
- (void)isItTheFirstTimeAfterUpdate {
NSString *versionnum;
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"yourplist.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:path]) {
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"yourplist" ofType:#"plist"];
[fileManager copyItemAtPath:bundle toPath:path error:&error];
}
NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
versionnum = #"";
//it can be installed by user (for ex. it is 1.3 but first installed), no plist value is set before
if(([savedStock objectForKey:#"versionnum"]) && (![[savedStock objectForKey:#"versionnum"] isEqualToString:#""])){
versionnum = [savedStock objectForKey:#"versionnum"];
}
//to get the version of installed/updated-current app
NSString *myversion = [NSString stringWithFormat:#"%#",[[[NSBundle mainBundle] infoDictionary] objectForKey:#"CFBundleVersion"]];
//if no version has been set-first install- or my version is the latest version no need to do sth.
if ([versionnum isEqualToString:myversion] || [versionnum isEqualToString:#""]) {
NSLog(#"Nothing has to be done");
}
else {
[self cleanDB];//i have clean tables and create my new db tables maybe logout the user etc.
[savedStock setObject:[NSString stringWithString:myversion] forKey:#"versionnum"];//setting the new version
[savedStock writeToFile:path atomically:YES];
}
}
And you can call the function in application launch or in your main view controller's view controller.. your choice.
hope it helps.
In my MainViewController I am using this code:
static NSBundle *bundle = nil;
+(void)setLanguage:(NSString *)l {
NSLog(#"preferredLang: %#", l);
NSString *path = [[ NSBundle mainBundle ] pathForResource:l ofType:#"lproj" ];
bundle = [[NSBundle bundleWithPath:path] retain];}
+(void)initialize {
NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
NSArray* languages = [defs objectForKey:#"AppleLanguages"];
NSString *current = [[languages objectAtIndex:0] retain];
[self setLanguage:current];
}
+(NSString *)get:(NSString *)key alter:(NSString *)alternate {
return [bundle localizedStringForKey:key value:alternate table:nil];}
And in application main:
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:#"tr", #"en", nil] forKey:#"AppleLanguages"];
Its working fine and showing the turkish language in my application other than the iPhone native language. But, I want to allow the user to change the language through buttons, like if user clicks on english language button, a dialogue should open that application will be restarted and your lang will be changed.
How to do that?
I am using iOS 5....
Your app should not provide a custom language selector.
Users probably have prior knowledge on how to change the preferred language by navigating to General > International > Language in the Settings application.
Further details in Apple's Internationalization Programming Guide
I have couple of applications alive in Apple store and we have just released updated version of these applications with incremented version numbers. I found that all resources are getting updated correctly(updated splash screen, background image etc) but newly added features are not getting updated. For example, I have included a feature so that iPhone app takes new contents from my website. It doesn't happen when I update the application from Appstore updates list.
...but the other strange thing is if I delete the application from my iPhone and download it again from Apple store then everything works fine!! I am not able to understand what has been going on. Anyone could please help me to debug this?
From this I got following code and added in my AppDelegate. For me it always print Version (null). I could see version number correctly set in my Application-info.plist file though!
#if DDEBUG // debugging/testing
NSString *versionString = [NSString stringWithFormat:#"v%#",[[NSBundle mainBundle] objectForInfoDictionaryKey:#"CFBundleVersion"]];
#else
NSString *versionString = [NSString stringWithFormat:#"Version %#",[[NSBundle mainBundle] objectForInfoDictionaryKey:#"CFBundleShortVersionString"]];
#endif // DDEBUG
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:versionString forKey:#"version"];
printf("Version: = %s\n", [versionString cStringUsingEncoding:NSMacOSRomanStringEncoding]);
[defaults synchronize]; // force immediate saving of defaults.
Following code works though! I mean it prints the correct version available in application-info.plist file! Got it from here
NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:#"CFBundleVersion"];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSLog(#"Version: %#", version);
[defaults setObject:version forKey:#"version_preference"];
[defaults synchronize];
I can confirm if this fixes the issue after resubmitting the application.
Thanks.
This worked:
NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:#"CFBundleVersion"];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSLog(#"Version: %#", version);
[defaults setObject:version forKey:#"version_preference"];
[defaults synchronize];
When testing my app on the simulator, I like the ability to edit, or even trash the apps plist file (which contains the NSUserDefaults) from the iPhone Simulator folder. This proves useful when testing (e.g. your app stores a dictionary in there, but you change the model/keys that you use for this data, and therefore need to remove the dictionary stored).
Is it possible to access this file on device (for your own app), without jailbreak?
Thanks in advance
The file is in Library/Preferences. The file is a binary plist with name <iOS application target identifier>.plist (look for the Identifier field in your app target settings), or list the directory contents:
NSString *path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
You could also load clean defaults with a #ifdef macro based on some env variable:
#ifdef TESTING
// use the code provided by tsakoyan below
#endif
If you care only for the NSUserDefaults values, this should trash/restore to global defaults all its custom data
NSDictionary *userDefDic = [[NSUserDefaults standardUserDefaults] dictionaryRepresentation];
NSArray *keys = [NSArray arrayWithArray:[userDefDic allKeys]];
for (NSString *key in keys) {
[[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
}
[[NSUserDefaults standardUserDefaults] synchronize];