需求描述:
打一次包,用户可以自由切换开发和生产环境
实现原理
每一个app在设置界面可以增加配置选项,存的数据可以通过user default读取,根据存储的数据来甄别切换网络
实现步骤
- 新增setting bundle
root.plist source code 如下
1 | <?xml version="1.0" encoding="UTF-8"?> |
效果:
代码获取值
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
31
32
33
34
35
36
37
38
39
40
41- (void)registerDefaultsFromSettingsBundle{
NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"];
if(!settingsBundle) {
NSLog(@"Could not find Settings.bundle");
return;
}
NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:@"Root.plist"]];
NSArray *preferences = [settings objectForKey:@"PreferenceSpecifiers"];
NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]];
for(NSDictionary *prefSpecification in preferences) {
NSString *key = [prefSpecification objectForKey:@"Key"];
if(key) {
[defaultsToRegister setObject:[prefSpecification objectForKey:@"DefaultValue"] forKey:key];
}
}
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister];
}
-(NSString *)getNetworkOption{
#if DEBUG
id obj = [[NSUserDefaults standardUserDefaults] objectForKey:@"env_key"];
if ([obj isKindOfClass:[NSString class]]) {
return (NSString *)obj;
}
return @"";
#else
return @"";
#endif
}
设置release状态不包含bundle文件
Xcode—->Project—->Build Settings—->Build Options—->Exclude Source Files Names—->Release 把文件拖进去
完。