Localisator.m 5.6 KB
//
//  Localisator.m
//  CustomLocalisator
//
//  Created by Michael Azevedo on 05/03/2014.
//

#import "Localisator.h"

static NSString * const kSaveLanguageDefaultKey = @"kSaveLanguageDefaultKey";
static NSString * const kSaveSystemLanguageKey = @"kSaveSystemLanguageKey";

@interface Localisator()

@property NSDictionary * dicoLocalisation;
@property NSUserDefaults * defaults;

@end

@implementation Localisator


#pragma  mark - Singleton Method

+ (Localisator*)sharedInstance
{
    static Localisator *_sharedInstance = nil;
    
    static dispatch_once_t oncePredicate;
    
    dispatch_once(&oncePredicate, ^{
        _sharedInstance = [[Localisator alloc] init];
    });
    return _sharedInstance;
}


#pragma mark - Init methods

- (id)init
{
    self = [super init];
    if (self)
    {
        _defaults                   = [NSUserDefaults standardUserDefaults];
        _availableLanguagesArray        = @[kSimplifiedChinese, kTraditionalChinese, kEnglish];
        _dicoLocalisation               = nil;
        _currentLanguage                = @"DeviceLanguage";
        
        NSString *languageSaved = nil;
        
        //系统语言优先级最高
        NSString *savedSystemLanguage = [_defaults objectForKey:kSaveSystemLanguageKey];
        
        NSString *currentSystemLanguage = [[[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"] objectAtIndex:0];
        
        if ([currentSystemLanguage hasPrefix:@"zh-Hans"]) {
            currentSystemLanguage = kSimplifiedChinese;
        }
        if ([currentSystemLanguage hasPrefix:@"zh-Hant"] || [currentSystemLanguage isEqualToString:@"zh-HK"] || [currentSystemLanguage isEqualToString:@"zh-TW"]) {
            currentSystemLanguage = kTraditionalChinese;
        }
       
        if (![currentSystemLanguage isEqualToString:savedSystemLanguage]) {
            [_defaults setObject:currentSystemLanguage forKey:kSaveSystemLanguageKey];
            
            if ([currentSystemLanguage isEqualToString:kSimplifiedChinese] || [currentSystemLanguage isEqualToString:kTraditionalChinese]) {
                languageSaved = currentSystemLanguage;
            }
            else {
                languageSaved = kEnglish;
            }
            
            if ([self loadDictionaryForLanguage:languageSaved]) {
                self.saveInUserDefaults = YES;
            }
        }
        else {
            languageSaved = [_defaults objectForKey:kSaveLanguageDefaultKey];
            
            if (languageSaved && ![languageSaved isEqualToString:@"DeviceLanguage"])
            {
                [self loadDictionaryForLanguage:languageSaved];
            }
            else {
                if ([currentSystemLanguage isEqualToString:kSimplifiedChinese] || [currentSystemLanguage isEqualToString:kTraditionalChinese]) {
                    languageSaved = currentSystemLanguage;
                }
                else {
                    languageSaved = kEnglish;
                }
                
                if ([self loadDictionaryForLanguage:languageSaved]) {
                    self.saveInUserDefaults = YES;
                }
            }
        }
    }
    return self;
}


#pragma mark - saveInIUserDefaults custom accesser/setter

-(void)setSaveInUserDefaults:(BOOL)saveInUserDefaults
{
    if (saveInUserDefaults)
    {
        [self.defaults setObject:_currentLanguage forKey:kSaveLanguageDefaultKey];
    }
    else
    {
        [self.defaults removeObjectForKey:kSaveLanguageDefaultKey];
    }
    [self.defaults synchronize];
}

#pragma mark - Private  Instance methods

-(BOOL)loadDictionaryForLanguage:(NSString *)newLanguage
{
    NSURL * urlPath = [[NSBundle bundleForClass:[self class]] URLForResource:@"Localizable" withExtension:@"strings" subdirectory:nil localization:newLanguage];
    if ([[NSFileManager defaultManager] fileExistsAtPath:urlPath.path])
    {
        self.currentLanguage = [newLanguage copy];
        self.dicoLocalisation = [[NSDictionary dictionaryWithContentsOfFile:urlPath.path] copy];
        
        return YES;
    }
    return NO;
}


#pragma mark - Public Instance methods

-(NSString *)localizedStringForKey:(NSString*)key
{
    if (self.dicoLocalisation == nil)
    {
        return NSLocalizedString(key, key);
    }
    else
    {
        NSString * localizedString = self.dicoLocalisation[key];
        if (localizedString == nil)
            localizedString = key;
        return localizedString;
    }
}

-(BOOL)setLanguage:(NSString *)newLanguage
{
    if (newLanguage == nil || [newLanguage isEqualToString:self.currentLanguage] || ![self.availableLanguagesArray containsObject:newLanguage])
        return NO;
    
    NSDictionary *dic = @{kLastLanguage: self.currentLanguage, kCurrentLanguage : newLanguage};
    
    if ([newLanguage isEqualToString:@"DeviceLanguage"])
    {
        self.currentLanguage = [newLanguage copy];
        self.dicoLocalisation = nil;
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationLanguageChanged
                                                            object:nil
                                                          userInfo:dic];
        return YES;
    }
    else
    {
        BOOL isLoadingOk = [self loadDictionaryForLanguage:newLanguage];
        
        if (isLoadingOk)
        {
            self.saveInUserDefaults = YES;
            
            [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationLanguageChanged
                                                                object:nil
                                                              userInfo:dic];
            
        }
        return isLoadingOk;
    }
}


@end