APIのURLが本番とテストで違う時などに、いちいちソースを直してビルドするのは面倒だし、間違ってテストのままストアにあげちゃったりするリスクがある。
Xcodeの機能のひとつ Preprocessor Macros を使う
こんな感じにheaderファイルで #ifdef DEBUG
を使って分ける。
#ifdef DEBUG
#define SERVER @"http://api.test.com"
#else
#define SERVER @"http://api.prod.com"
#endif
Sample実装
すべてのViewControllerにかくのは面倒なのでPrefix headerにかく。
ProjectName > Supporting Files > {ProjectName}-Prefix.pch
//
// Prefix header
//
// The contents of this file are implicitly included at the beginning of every source file.
//
#import <Availability.h>
#ifndef __IPHONE_5_0
#warning "This project uses features only available in iOS SDK 5.0 and later."
#endif
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#endif
//テストと本番のサーバー設定
#ifdef DEBUG
#define SERVER @"http://api.test.com"
#else
#define SERVER @"http://api.prod.com"
#endif
この状態でビルドすると、#ifdef DEBUG のほうに入る。
本番環境でビルドしたいときはShemeを変更する。
Xcode > Product > Scheme > Edit Scheme... > Build Configuration
ここを Debug
から Release
に変更してビルドすると #else に入る。
ログの出力とかにも使えるかも。
便利便利。