LoginSignup
16
15

More than 5 years have passed since last update.

Xcode Preprocessor Macrosを使って本番とテストをコントロール

Posted at

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 に入る。

ログの出力とかにも使えるかも。
便利便利。

16
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
15