How can I change application language inside the application? - ios

I would like to change application language inside the app without restarting.
There are Localizable.strings files for both languages. All my XIBs and main Storyboard too.
Te below code can change the language only after restarting an app
main.m:
int main(int argc, char *argv[])
{
NSString *currLang = [[NSUserDefaults standardUserDefaults] stringForKey:#"Lang"];
if (!currLang) {
NSString *languageCode = [[NSLocale preferredLanguages] objectAtIndex:0];
if ([languageCode isEqualToString:#"ru"]) {
[[NSUserDefaults standardUserDefaults] setValue:languageCode forKey:#"Lang"];
}
else [[NSUserDefaults standardUserDefaults] setValue:#"en" forKey:#"Lang"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
currLang = nil;
currLang = [[NSUserDefaults standardUserDefaults] stringForKey:#"Lang"];
if ([currLang isEqualToString:#"ru"]) {
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:#"ru", #"en", nil]
forKey:#"AppleLanguages"];
}
else
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:#"en", #"ru", nil]
forKey:#"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];
#autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
There are 2 buttons (Eng & Ru) ant the method:
- (IBAction)changeLang:(UIButton *)sender
{
if ([sender isEqual:btnSetRuLang]) {
if ([[userDefaults stringForKey:#"Lang"] isEqualToString:#"ru"]) {
return;
}
[userDefaults setValue:#"ru" forKey:#"Lang"];
[userDefaults synchronize];
}
else {
if ([[userDefaults stringForKey:#"Lang"] isEqualToString:#"en"]) {
return;
}
[userDefaults setValue:#"en" forKey:#"Lang"];
[userDefaults synchronize];
}
NSString *currLang = [userDefaults stringForKey:#"Lang"];
NSString *alertBody;
if ([currLang isEqualToString:#"ru"]) {
[userDefaults setObject:[NSArray arrayWithObjects:#"ru", #"en", nil]
forKey:#"AppleLanguages"];
alertBody = #"Перезапустите приложение для смены языка";
}
else {
[userDefaults setObject:[NSArray arrayWithObjects:#"en", #"ru", nil]
forKey:#"AppleLanguages"];
alertBody = #"Restart application for change language";
}
[userDefaults synchronize];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Hom" message:alertBody delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alertView show];
}
So, how should I change lang without restarting app?
Thank you.

I have did the same in one of my application, When user changes the language I did the same and reload all my View controllers which are in navigation stack by calling setNeedsDisplay, that renders the view again with new language settings.
EDIT
for each instance of your view controller call [self setNeedsDisplay] or you can replace the self by the instance of your view controller.

I would suggest you to use
NSLocalizedStringFromTable(key, tbl, comment)
instead of NSLocalizedString(key, comment)
This way all you need to do is maintain a variable of table name. Instead of Localizable.strings, use en.strings and ru.strings files and when the language changes pass the table name as en or ru
Also as #Parser suggests, you must refresh your views.

Related

iOS: Force view reload after locale change

I have setup my app to support a base internationalization for English and added a local for Spanish. I'm trying to provide an option to force the app to use a locale select by the user via a segmented control.
What I would like to do is have the screen "refresh" or "redraw" with the new selected locale.
Here is my action for the segmented control:
- (IBAction)segmentSwitch:(id)sender {
UISegmentedControl *segmentedControl = (UISegmentedControl *) sender;
NSInteger selectedSegment = segmentedControl.selectedSegmentIndex;
NSUserDefaults *prefs;
prefs = [NSUserDefaults standardUserDefaults];
if (selectedSegment == 0) {
[prefs setObject:#"en" forKey:#"language"];
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:#"en", nil] forKey:#"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"English");
}
else
{
[prefs setObject:#"es" forKey:#"language"];
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:#"es", nil] forKey:#"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"Spanish");
}
[self.view setNeedsDisplay];
}
My hope is that the screen would refresh and display the selected language view. If I close out the app and restart, it does display new view.
Here is my viewWillAppear:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// get the saved language preference
NSUserDefaults *prefs;
prefs = [NSUserDefaults standardUserDefaults];
NSString *stringVal = [prefs stringForKey:#"language"];
// Make sure we have a valid value
if (stringVal != nil) {
// Set the language preference
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:stringVal, nil] forKey:#"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize]; //to make the change immediate
// Turn on the appropriate segment
if ([stringVal isEqual: #"en"]) {
NSLog(#"English");
languageSwitch.selectedSegmentIndex = 0;
} else {
NSLog(#"Spanish");
languageSwitch.selectedSegmentIndex = 1;
}
} else {
// default to English
languageSwitch.selectedSegmentIndex = 0;
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:#"en", nil] forKey:#"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize]; //to make the change immediate
}
}
I had thought that following would force a screen refresh but it doesn't seem to be working:
[self.view setNeedsDisplay];
Any thoughts or suggestions would be appreciated. Thanks in advanced.

Press twice for before function starts Objective-C

sorry if the title is a bit sloppy or confusing, I'll try to explain it a bit more detailed.
I have a function in my app which allows users to only use it 10 times a day. The code below handles the counting per day which is actually working good except that the user always have to press twice on a new loop before it's getting called.
I think it has something to do with the fabs function, or what could be the reason the user has to press twice on a new loop?
-(void)dailyCount:(id)sender{
NSString *kFirstLaunchDateKey = #"tenPerDay";
NSDate *firstLaunchDate = [[NSUserDefaults standardUserDefaults] objectForKey:kFirstLaunchDateKey];
NSInteger count = [[NSUserDefaults standardUserDefaults] integerForKey:#"perDay"];
if (!firstLaunchDate) {
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:kFirstLaunchDateKey];
[[NSUserDefaults standardUserDefaults] setInteger:count+1 forKey:#"perDay"];
return;
}
NSTimeInterval diff = fabs([firstLaunchDate timeIntervalSinceNow]);
if (diff > 60 * 60 * 24 * 1) {
[[NSUserDefaults standardUserDefaults] removeObjectForKey:#"tenPerDay"];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:#"perDay"];
}else{
if (count % 11 == 0) {
[UIAlertView showWithTitle:#"Daily Limit Exceeded"
message:#"Sorry, you can use this option only 10 times per day."
cancelButtonTitle:#"Ok"
otherButtonTitles:nil
tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
if (buttonIndex == [alertView cancelButtonIndex]) {
}
}];
}else {
// do something here... (Have to press twice on a new loop before it's getting called)
[[NSUserDefaults standardUserDefaults] setInteger:count+1 forKey:#"perDay"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
}
-(void)dailyCount:(id)sender{
NSString *kFirstLaunchDateKey = #"tenPerDay";
NSDate *firstLaunchDate = [[NSUserDefaults standardUserDefaults] objectForKey:kFirstLaunchDateKey];
if (!firstLaunchDate) {
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:kFirstLaunchDateKey];
[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:#"perDay"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self counterNew];
return;
}
NSTimeInterval diff = fabs([firstLaunchDate timeIntervalSinceNow]);
if (diff > 60 * 60 * 24 * 1) {
[[NSUserDefaults standardUserDefaults] removeObjectForKey:#"tenPerDay"];
[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:#"perDay"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self counterNew];
}else{
[self counterNew];
}
}
-(void)counterNew{
NSInteger count = [[NSUserDefaults standardUserDefaults] integerForKey:#"perDay"];
if (count > 10) {
[UIAlertView showWithTitle:#"Daily Limit Exceeded"
message:#"Sorry, you can use this option only 10 times per day."
cancelButtonTitle:#"Ok"
otherButtonTitles:nil
tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
if (buttonIndex == [alertView cancelButtonIndex]) {
}
}];
}else {
//Do something here...
[[NSUserDefaults standardUserDefaults] setInteger:count+1 forKey:#"perDay"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}

Can't set NSUserDefaults value through variable in IOS

In my iOS app when I'm logging in I used set UserID and loginstatus into NSUserDefaults like this.
#implementation Login{
NSInteger UserId;
NSUserDefaults *preferences;
}
- (IBAction)LogInClick:(UIButton *)sender {
[preferences setInteger:UserId forKey:#"UserId"]; //UserId=40;
[preferences setBool:YES forKey:#"loginstatus"];
[preferences synchronize];
NSLog(#"All NSUserDefaults: %#", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
NSString *uID = [preferences stringForKey:#"UserId"];
NSLog(#"UserID: %#",uID);
}
But the values are not setting in the NSUserDefaults. I tried to log all NSUserDefaults value and also the single UserID value but all fields are coming null.
Later I use this code to logout
- (IBAction)LogOutClick:(UIButton *)sender {
[[NSUserDefaults standardUserDefaults] setObject:0 forKey:#"UserId"];
[[NSUserDefaults standardUserDefaults] setObject:NO forKey:#"loginstatus"];
/* [preferences setInteger:0 forKey:#"UserId"];
[preferences setBool:NO forKey:#"loginstatus"];
[preferences synchronize];*/
NSLog(#"All NSUserDefaults: %#", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
}
First when i logged out it all sets to zero and now the values are not setting. Can anybody tell me what the problem is?
That's because NSUserDefaults *preferences; is just a pointer. And it's value is nil, I presume. You should initialize it. For instance:
- (IBAction)LogInClick:(UIButton *)sender {
preferences = [NSUserDefaults standardUserDefaults];
[preferences setInteger:UserId forKey:#"UserId"]; //UserId=40;
[preferences setBool:YES forKey:#"loginstatus"];
[preferences synchronize];
...
May be a more logical place to initialize preferences would be an init method, or something else that you would consider appropriate for this purpose.
You haven't get the standard userdefaults reference. Change this method
- (IBAction)LogInClick:(UIButton *)sender {
preferences = [NSUserDefaults standardUserDefaults];
[preferences setInteger:UserId forKey:#"UserId"]; //UserId=40;
[preferences setBool:YES forKey:#"loginstatus"];
[preferences synchronize];
NSLog(#"All NSUserDefaults: %#", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
NSString *uID = [preferences stringForKey:#"UserId"];
NSLog(#"UserID: %#",uID);
}

Detect if user opened the View for the first Time In iOS

I know how I can detect if the application first time opened using NSUserDefault:
BOOL didRunBefore = [[NSUserDefaults standardUserDefaults] boolForKey:#"didRunBefore"];
if (!didRunBefore) {
//Your Launch Code
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"didRunBefore"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
The Issue: I want an Alert for ever view explaining about what features it contains and only open this alert when the app is first launched?
As an OOP programmer you can make a common public method.
+ (BOOL)checkWhetherRunBefore:(NSString *)key
{
return [[NSUserDefaults standardUserDefaults] boolForKey:key];
}
+ (void)hasRunForMyClass:(NSString *)key
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:key];
[[NSUserDefaults standardUserDefaults] synchronize];
}
And in your ViewController , you can code in the viewWillAppear or viewDidAppear like this :
- (void)viewWillAppear
{
if(![HelpController checkWhetherRunBefore:NSStringFromClass([self class])])
{
//do your thing
[HelpController hasRunForMyClass:NSStringFromClass([self class])]
}
}
You just need to put your code in viewDidLoad
viewDidLoad will run only one time when app load your view. (except low memory)
Next time you load the view again in viewDidLoad, you can check bool didRunBefore
You can use any key you want.
In FirstViewController:
BOOL didRunBefore = [[NSUserDefaults standardUserDefaults] boolForKey:#"FirstViewController_didRunBefore"];
if (!didRunBefore) {
//Your Launch Code
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"FirstViewController_didRunBefore"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
In SecondViewController:
BOOL didRunBefore = [[NSUserDefaults standardUserDefaults] boolForKey:#"SecondViewController_didRunBefore"];
if (!didRunBefore) {
//Your Launch Code
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"SecondViewController_didRunBefore"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
yo have to need to detect application first launch, you can detect t like this
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![defaults objectForKey:#"firstRun"])
[defaults setObject:[NSDate date] forKey:#"firstRun"];
[[NSUserDefaults standardUserDefaults] synchronize];
You can then test for it later...
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if([defaults objectForKey:#"firstRun"])
{
// do something or not...
}

Setting/Saving UISwitch State using NSUserDefaults Proofread

Developing for a jailbroken device.
I've looked here for a soultion to my problem. Using NSUserDefaults for storing UISwitch state but people say alot of the codes don't work.
I'm using a UISwitch to load/unload a launch daemon for iOS. I've gotten very close but the switch state won't save. This is the code im using.
#synthesize toggleSwitch;
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if([[NSUserDefaults standardUserDefaults] boolForKey:#"switch"]) toggleSwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:#"switch"];
}
- (void)switchValueChanged {
if (toggleSwitch.on) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:TRUE];
switchlabel.text = #"Enabled";
const char *onchar = [[NSString stringWithString:#"launchctl load -wF /System/Library/LaunchDaemons/com.launch.daemon.plist"] UTF8String];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];
setuid(0); system(onchar);
if (system(onchar) == 0){
[[NSUserDefaults standardUserDefaults] setBool:self.toggleSwitch.on forKey:#"switch"];
[[NSUserDefaults standardUserDefaults] synchronize];
} else {
[[NSUserDefaults standardUserDefaults] setBool:self.toggleSwitch.on forKey:#"switch"];
[[NSUserDefaults standardUserDefaults] synchronize];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];}
} else {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:TRUE];
switchlabel.text = #"Disabled";
const char *offchar = [[NSString stringWithString:#"launchctl unload -wF /System/Library/LaunchDaemons/com.launch.daemon.plist"] UTF8String];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE];
setuid(0); system(offchar);
if (system(offchar) == 0){
[[NSUserDefaults standardUserDefaults] setBool:self.toggleSwitch.on forKey:#"switch"];
[[NSUserDefaults standardUserDefaults] synchronize];
} else {
[[NSUserDefaults standardUserDefaults] setBool:self.toggleSwitch.on forKey:#"switch"];
[[NSUserDefaults standardUserDefaults] synchronize];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:FALSE]; }
}
The bool value is written in my app plist. I don't seem to know what I did wrong. I pieced afew examples from questions on overflow with no luck. Regardless if the command fails, the switch should save.
Could someone explain and show me what should be edited. This has been driving me absolutely nuts.

Resources