開發(fā)時候,為了調(diào)試bug或者查看正式服數(shù)據(jù),經(jīng)常在內(nèi)網(wǎng)和外網(wǎng)之間,為了方便測試,添加一個按鈕,一鍵切換內(nèi)外網(wǎng),如圖所示.
demo.gif
由于比較簡單,直接上代碼
MFChangeServer.h
@interface MFChangeServer : NSObject
+ (void)change;// 切換內(nèi)外網(wǎng),自由debug 模式有效
+ (NSString *)commonUrl;// 切換內(nèi)外網(wǎng),自由debug 模式有效
+ (NSString *)baseUrl;// 切換內(nèi)外網(wǎng),自由debug 模式有效
+ (NSString *)shareUrl;// 切換內(nèi)外網(wǎng),自由debug 模式有效
@end
MFChangeServer.m
#import "MFChangeServer.h"
static int index_MF_NODup = 0;
@implementation MFChangeServer
+ (void)change{
index_MF_NODup++;
index_MF_NODup = index_MF_NODup%2;
}
+ (NSString *)baseUrl{
static NSArray *array = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
array = @[@"https://正式服地址",
@"https://測試服地址"
];
});
return array[index_MF_NODup];
}
+ (NSString *)commonUrl{
static NSArray *array = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
array = @[@"https://正式服地址",
@"https://測試服地址"
];
});
return array[index_MF_NODup];
}
+ (NSString *)shareUrl{
static NSArray *array = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
array = @[@"https://正式服地址",
@"https://測試服地址"
];
});
return array[index_MF_NODup];
}
@end
用法
在定義根路徑的地方
#define kCommonUrl [MFChangeServer commonUrl]
#define kBaseUrl [MFChangeServer baseUrl]
#define kShareBaseUrl [MFChangeServer shareUrl]
在.pch文件添加頭文件
#ifdef __OBJC__
#import "MFChangeServer.h"
#endif
需要注意的是此處不能用懶加載
attention.png
設置界面右上角添加按鈕
#ifdef DEBUG
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"切換" style:UIBarButtonItemStylePlain target:self action:@selector(changeServer)];
#endif
- (void)changeServer{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"切換服務器" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"確定", nil];
alert.delegate = self;
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex != alertView.cancelButtonIndex) {
[MFChangeServer change];
}
}
copyright by 我的同事-偉