Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload the app programmatically in swift

Tags:

ios

swift

I created localization for my storyboard (English, Arabic) and I did the function that changes (switch) the App. language (local) it's working perfect if I restart (relaunch) the app manually and my Views flip Right-Let if Arabic and Left-Right if English as well, but how can I change the storyboard local without restarting my app manually?.

I used this function to change the language

 func setLocale(langCode:String){

    NSUserDefaults.standardUserDefaults().setObject([langCode], forKey: "AppleLanguages")
    NSUserDefaults.standardUserDefaults().synchronize()

}

Thank in advance.

like image 392
Diyaa Avatar asked Oct 18 '22 00:10

Diyaa


1 Answers

This is how you can do. However this code is in Obj-C.

Create a category class for NSBundle like this:

#import "NSBundle+ForceLocalization.h"
#import <objc/runtime.h>


static const char _bundle=0;
@interface BundleEx : NSBundle
@end

@implementation BundleEx

-(NSString*)localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)tableName
{
    NSBundle* bundle=objc_getAssociatedObject(self, &_bundle);
    return bundle ? [bundle localizedStringForKey:key value:value table:tableName] : [super localizedStringForKey:key value:value table:tableName];
}
@end

@implementation NSBundle (ForceLocalization)

+(void)setLanguage:(NSString*)language
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^
                  {
                      object_setClass([NSBundle mainBundle],[BundleEx class]);
                  });
    objc_setAssociatedObject([NSBundle mainBundle], &_bundle, language ? [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:language ofType:@"lproj"]] : nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end

After this, simply call:

[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects: langCode, nil]
                                                  forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];
[NSBundle setLanguage: langCode];

You need to reload the UI for the current screen again. If you go on to another controller, you'll see the updated language.

like image 53
Bhavuk Jain Avatar answered Nov 03 '22 19:11

Bhavuk Jain