App內(nèi)實現(xiàn)語言國際化(OC和Swift)

1讽挟、OC實現(xiàn)語言國際化(NSBundle擴展)

.h文件

#import <Foundation/Foundation.h>

@interface NSBundle (Language)

+ (void)setLanguage:(NSString *)language;

@end

```
.m文件

```
#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 (Language)
    
+ (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

```
使用方法:
```
1、在AppDelegate中:
NSString *currentLanguage = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
if (currentLanguage) {
     [NSBundle setLanguage:currentLanguage];
}

2扳还、選擇語言時保存:
[[NSUserDefaults standardUserDefaults] setObject:currentLanguage forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];

[NSBundle setLanguage:currentLanguage];

3淤堵、在需要國際化的地方使用     NSLocalizedString(key, @"");

4嘀掸、重新設(shè)置Root
```
2涯竟、Swift實現(xiàn)語言國際化
######1、Bundle擴展
```
/**
 *  當(dāng)調(diào)用onLanguage后替換掉mainBundle為當(dāng)前語言的bundle
 */
class BundleEx: Bundle {
    
    override func localizedString(forKey key: String, value: String?, table tableName: String?) -> String {
        if let bundle = languageBundle() {
            return bundle.localizedString(forKey: key, value: value, table: tableName)
        } else {
            return super.localizedString(forKey: key, value: value, table: tableName)
        }
    }
}

extension Bundle {
    
    //代替dispatch_once
    private static var onLanguageDispatchOnce: ()->Void = {
        object_setClass(Bundle.main, BundleEx.self)
    }
    
    func onLanguage() {
        //替換NSBundle.mainBundle()的class為自定義的BundleEx谚咬,這樣一來我們就可以重寫方法
        Bundle.onLanguageDispatchOnce()
    }
    
    //當(dāng)前語言的bundle
    func languageBundle() -> Bundle? {
        return Languager.standardLanguager().currentLanguageBundle
    }
}

```
######2鹦付、添加Languager類
```
private let kUserLanguage = "AppleLanguages"

/**
 *  國際化工具
 */
class Languager: NSObject {
    
    private static var __once: () = {
            Static.staticInstance = Languager()
    }()
    
    fileprivate struct Static {
        static var onceToken : Int = 0
        static var staticInstance : Languager? = nil
    }
    
    // 單例
    class func standardLanguager()->Languager{
        _ = Languager.__once
        return Static.staticInstance!
    }

    fileprivate var _currentLanguage:String?
    
    override init() {
        super.init()
        self.initLanguages()
    }
    
    //當(dāng)前語言Bundle
    internal var currentLanguageBundle:Bundle?
    
    // 當(dāng)前語言獲取與切換
    var currentLanguage:String {
        get{
            if(self._currentLanguage==nil){
                self._currentLanguage = (UserDefaults.standard.value(forKey: kUserLanguage) as! Array<String>)[0]
            }
            return self._currentLanguage!
        }
        set(newLanguage){
            if(self._currentLanguage == newLanguage){
                return
            }
            if let path = Bundle.main.path(forResource: newLanguage, ofType: "lproj" ),let bundel = Bundle(path:path){
                self.currentLanguageBundle = bundel
                self._currentLanguage = newLanguage
            }else{
                //如果不支持當(dāng)前語言則加載info中Localization native development region中的值的lporj
                let defaultLanguage = (Bundle.main.infoDictionary! as NSDictionary).value(forKey: kCFBundleDevelopmentRegionKey as String) as! String
                self.currentLanguageBundle =  Bundle(path:Bundle.main.path(forResource: defaultLanguage, ofType: "lproj" )!)
                self._currentLanguage = defaultLanguage
            }
            let def = UserDefaults.standard
            def.setValue([self._currentLanguage!], forKey:kUserLanguage)
            def.synchronize()
            
            Bundle.main.onLanguage()
        }
    }
    
    //初始化
    func initLanguages(){
        let language = (UserDefaults.standard.object(forKey: kUserLanguage) as! Array<String>)[0]
        if let path = Bundle.main.path(forResource: language, ofType: "lproj" ),let bundel = Bundle(path:path) {
            self.currentLanguageBundle = bundel
            self._currentLanguage = language
        } else {
            //如果不支持當(dāng)前語言則加載info中Localization native development region中的值的lporj,設(shè)置為當(dāng)前語言
            self.currentLanguage = (Bundle.main.infoDictionary! as NSDictionary).value(forKey: kCFBundleDevelopmentRegionKey as String) as! String
            print("Languager:\(language)不支持,切換成默認語言\(self._currentLanguage!)")
        }
    }
    
    
    /**
     獲取當(dāng)前語言的string
     */
    func string(_ key:String) -> String {
        if let str = self.currentLanguageBundle?.localizedString(forKey: key, value: nil, table: nil){
            return str
        }
        return key
    }
    
}

func localized(_ key:String) -> String {
    return Languager.standardLanguager().string(key)
}

```
使用方法:
```
Languager.standardLanguager().currentLanguage = currentLanguages

在需要國際化的地方使用     localized(key)

```

注意:新建String File時择卦,文件名一定要是Localizable,否則無效郎嫁!

![Snip20170721_1.png](http://upload-images.jianshu.io/upload_images/2107724-5b75ba103e56daff.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末秉继,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子泽铛,更是在濱河造成了極大的恐慌尚辑,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,546評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件盔腔,死亡現(xiàn)場離奇詭異杠茬,居然都是意外死亡,警方通過查閱死者的電腦和手機弛随,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,224評論 3 395
  • 文/潘曉璐 我一進店門瓢喉,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人舀透,你說我怎么就攤上這事栓票。” “怎么了愕够?”我有些...
    開封第一講書人閱讀 164,911評論 0 354
  • 文/不壞的土叔 我叫張陵走贪,是天一觀的道長。 經(jīng)常有香客問我惑芭,道長坠狡,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,737評論 1 294
  • 正文 為了忘掉前任遂跟,我火速辦了婚禮逃沿,結(jié)果婚禮上婴渡,老公的妹妹穿的比我還像新娘。我一直安慰自己感挥,他們只是感情好缩搅,可當(dāng)我...
    茶點故事閱讀 67,753評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著触幼,像睡著了一般硼瓣。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上置谦,一...
    開封第一講書人閱讀 51,598評論 1 305
  • 那天堂鲤,我揣著相機與錄音,去河邊找鬼媒峡。 笑死瘟栖,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的谅阿。 我是一名探鬼主播半哟,決...
    沈念sama閱讀 40,338評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼签餐!你這毒婦竟也來了寓涨?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,249評論 0 276
  • 序言:老撾萬榮一對情侶失蹤氯檐,失蹤者是張志新(化名)和其女友劉穎戒良,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體冠摄,經(jīng)...
    沈念sama閱讀 45,696評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡糯崎,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,888評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了河泳。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片沃呢。...
    茶點故事閱讀 40,013評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖乔询,靈堂內(nèi)的尸體忽然破棺而出樟插,到底是詐尸還是另有隱情,我是刑警寧澤竿刁,帶...
    沈念sama閱讀 35,731評論 5 346
  • 正文 年R本政府宣布黄锤,位于F島的核電站,受9級特大地震影響食拜,放射性物質(zhì)發(fā)生泄漏鸵熟。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,348評論 3 330
  • 文/蒙蒙 一负甸、第九天 我趴在偏房一處隱蔽的房頂上張望流强。 院中可真熱鬧痹届,春花似錦、人聲如沸打月。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,929評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽奏篙。三九已至柴淘,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間秘通,已是汗流浹背为严。 一陣腳步聲響...
    開封第一講書人閱讀 33,048評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留肺稀,地道東北人第股。 一個月前我還...
    沈念sama閱讀 48,203評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像话原,于是被迫代替她去往敵國和親夕吻。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,960評論 2 355

推薦閱讀更多精彩內(nèi)容