如何在更改语言后强制用户重新启动应用程序

时间:2018-05-14 08:12:09

标签: ios objective-c iphone

该方案如下: 处理一个项目,使用户能够使用下拉列表选择他们的首选语言。

- (IBAction)languageBtnPressed:(UIButton *)sender {
    [[NSUserDefaults standardUserDefaults] setObject: [NSArray arrayWithObjects:@"en", nil] forKey:@"AppleLanguages"];
    [[NSUserDefaults standardUserDefaults] synchronize];

}

我打算强制用户使用exit(0)退出应用程序,当然是提示。这样可以加载可本地化的字符串。如何自动重新启动应用程序?提前谢谢。

2 个答案:

答案 0 :(得分:0)

您无法在IOS中重新启动该应用,用户已经拥有自行重新启动它的经验

答案 1 :(得分:0)

我有这段代码:

- (void)changeLanguage:(NSString *)newLang {
    [NSBundle setLanguage:newLang];
    [self reloadViewController];
}

NSBundle中的位置:

@implementation NSBundle (Language)

+ (void)setLanguage:(NSString *)language
{
    //if language not supported we default to spanish
    if (language == nil || ![SMLocalizedString isLanguageSupported:language]){
        //defaults to spanish
        language = @"es";
    }

    //Sotres new language setting in user 
    [SMLocalizedString updateCurrentLanguage:language];

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        object_setClass([NSBundle mainBundle], [BundleEx class]);
    });

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

    id value = language ? [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:language ofType:@"lproj"]] : nil;
    objc_setAssociatedObject([NSBundle mainBundle], &kBundleKey, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end

然后,我重新加载我的View Controller:

- (void)reloadViewController {
    SMAppDelegate *delegate = (SMAppDelegate *)[[UIApplication sharedApplication] delegate];
    UIStoryboard *storybaord = [UIStoryboard storyboardWithName:@"MainIpad" bundle:nil];
    delegate.window.rootViewController = [storybaord instantiateInitialViewController];
}