iOS高级文章

使用xcconfig文件定义多种环境变量

2017-08-19  本文已影响194人  DonnyDD

有的项目每次切换Debug、Release时,手动修改某个环境变量,比如服务器地址,SDK的key,id...之类的。如何在Debug、Release等模式下各自设置不同的环境变量值,可以使用xcconfig文件:

步骤:
1.创建Configs文件夹,cmd + N创建xcconfig文件(文件名可以随便取):

文件夹.png

创建xcconfig文件:New File ->iOS(Other) ->Configration Settings File

2.xcode配置
打开项目的workspace,进入xcode的主界面。选中主要工程的project -> info , 找到Configurations,如下配置:

xcode内配置.png

如果项目中有用到单元测试,这里把test的config文件设置为none:


单元测试target设置none.png

3.xcconfig文件内容怎么写:
DefaultConfig.xcconfig:

//因为项目中可能有多个Target,每个Target都需要创建多个环境;有时候他们都需要有个默认的配置,若在其他xcconfig文件不重写变量值,默认使用此文件的值
APP_NAME = ******
APP_VERSION = 1.2.6
APP_BUILD_VERSION = 25
APP_SLOGAN = ******

BrokerCommonConfig.xcconfig:

//注意要用#include导入头文件
#include "DefaultConfig.xcconfig"

BrokerDebugConfig.xcconfig:

//设置在Debug模式下使用的变量
#include "BrokerCommonConfig.xcconfig"
#include "Pods/Target Support Files/Pods-SofangBroker/Pods-SofangBroker.debug.xcconfig"
APP_NAME = APP名debug
APP_SLOGAN = sloganDebug

BrokerReleaseConfig.xcconfig:

//设置在Release模式下使用的变量
#include "BrokerCommonConfig.xcconfig"
#include "Pods/Target Support Files/Pods-SofangBroker/Pods-SofangBroker.release.xcconfig"
APP_NAME = APP名release
APP_SLOGAN = sloganRelease

这样编译一下,在Build Setting ->User-Defined中就有了(仅以Debug Release举例):

image.png
另外例如服务器地址有两套以上,(如测试-模拟-线上)可以添加其他新的Debug模式,并创建新的xcconfig文件,如下:

创建BrokerReleaseTestConfig.xcconfig文件,写好内容并且创建新的ReleaseTest模式,配置此文件:

//设置在ReleaseTest模拟模式下使用的变量
#include "BrokerCommonConfig.xcconfig"
#include "Pods/Target Support Files/Pods-SofangBroker/Pods-SofangBroker.debug.xcconfig"
APP_NAME = APP名releaseTest
APP_SLOGAN = sloganReleaseTest
创建新模式.png 创建新模式配置xcconfig文件.png

好啦,Edit Scheme中就会有Run->ReleaseTest模式了,可以任意切换:

ReleaseTest模式.png

命令行运行:

//坑!!!:不能用 pod install --verbose --no-repo-update
pod install

4.设置环境变量
把环境变量添加到Target->Info.plist文件中,例如设置:(注意$(...)格式)

Bundle name 为$(APP_NAME)
AppSlogan   为$(APP_SLOGAN)
info.png

这样就可以使用NSBundle从info.plist中获得此变量值了,不同模式下会从不同文件中取到不同值:

- (NSString *)getValueWithInfoKey:(NSString *)key{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *value = [infoDictionary objectForKey:key];
    return value ? value : @"";
}
...
NSLog(@"AppSlogan:%@",[self getValueWithInfoKey:@"AppSlogan"]);
//注意此处取AppName不能用@"AppName",因为上面设置的value对应key是Bundle name!所以用系统的kCFBundleNameKey
NSLog(@"AppSlogan:%@",[self getValueWithInfoKey:(NSString *)kCFBundleNameKey]);

需要注意的:修改xcconfig文件时,需要clean一下工程,可能有缓存。

另外说说定义全局宏的方式:
Project -> Build settings -> Apple LLVM 7.1 - Preprocessing 在 Preprocessor Macros中设置key=value,key即为全局宏,通常在此设置DEBUG=1

上一篇下一篇

猜你喜欢

热点阅读