iOS国际化中你可能会用到的一些小技巧

一:系统权限的提示语国际化

image.png

  1. 在项目内新建名称为 InfoPlist.strings 的文件
  2. 选好locallzation
    locallzation.png
  3. 进入info.plist,选择show Raw keys提取key
    image.png
  4. 将key 写入InfoPlist.strings:
    1
    2
    3
    NSAppleMusicUsageDescription = "You need to access media data to store pictures or videos.Do you allow access (yes or no)";
    NSMicrophoneUsageDescription = "Use a microphone to capture sound during live broadcast,Are you allowed to turn on the microphone.";
    NSPhotoLibraryAddUsageDescription = "You need to visit the album to select a picture,Do you allow access.";

二:LaunchScreen的国际化

很多时候我们也需要将启动页LaunchScreen国际化,可按照下面的步骤:

  1. info.plist内写入key:Launch screen interface file base name(有就不要写了) value:LaunchScreen
  2. 新建2个LaunchScree,名称为LaunchScreen_CH和LaunchScreen_EN
  3. InfoPlist.strings内对应的语言文件写入
    1
    2
    UILaunchStoryboardName = "LaunchScreen_EN"; (英文)
    UILaunchStoryboardName = "LaunchScreen_CH"; (中文)

LaunchScreen本来是可以直接选好locallzation然后国际化的,但是现在应该是苹果的bug,locallzation之后只显示英文,所以我选择用这种创建两个LaunchScreen的方式

三:获取系统当前的语言

1
2
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSArray *languages = [defaults objectForKey:@"AppleLanguages"];

四:MJRefresh的多语言加载

MJRefresh中添加多语言可以根据具体的业务需求改动,全局搜索这个方法:

1
+ (NSString *)mj_localizedStringForKey:(NSString *)key value:(NSString *)value

五:设置APP语言的工具类

1
2
3
4
5
6
7
# import <Foundation/Foundation.h>

@interface NSBundle (Language)

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

@end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#import "NSBundle+Language.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 (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
[NSBundle setLanguage:@"zh-Hans"];