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、重新設置Root
```
2、Swift實現(xiàn)語言國際化
######1、Bundle擴展
```
/**
 *  當調(diào)用onLanguage后替換掉mainBundle為當前語言的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()
    }
    
    //當前語言的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()
    }
    
    //當前語言Bundle
    internal var currentLanguageBundle:Bundle?
    
    // 當前語言獲取與切換
    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{
                //如果不支持當前語言則加載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 {
            //如果不支持當前語言則加載info中Localization native development region中的值的lporj,設置為當前語言
            self.currentLanguage = (Bundle.main.infoDictionary! as NSDictionary).value(forKey: kCFBundleDevelopmentRegionKey as String) as! String
            print("Languager:\(language)不支持,切換成默認語言\(self._currentLanguage!)")
        }
    }
    
    
    /**
     獲取當前語言的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)
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容