有时候测试要经常切换内网外网,查看数据,为了方便测试,写一个功能,在DeBug模式下只要一个按钮就可以一键切换内网外网。
效果图拓展功能类
- 直接上代码
*** ChangeServer.h***
#import <Foundation/Foundation.h>
@interface ChangeServer : NSObject
+ (void)changeServer:(int)serverName;
+ (NSString *)baseUrl;
+ (NSString *)imageRootUrl;
@end
*** ChangeServer.m***
#import "ChangeServer.h"
@implementation ChangeServer
static int indexServer = 0;
+ (void)changeServer:(int)serverName {
indexServer = serverName;
}
+ (NSString *)baseUrl {
static NSArray *array = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
array = @[@"http://正式服地址",
@"http://测试服地址",
@"http://本地测试地址"
];
});
return array[indexServer];
}
+ (NSString *)imageRootUrl {
static NSArray *array = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
array = @[@"http://正式服地址",
@"http://测试服地址",
@"http://本地测试地址"
];
});
return array[indexServer];
}
@end
用法实例
- 在定义基地址的地方
#define BASE_URL [ChangeServer baseUrl]
#define IMAGE_ROOT_URL [ChangeServer imageRootUrl]
- 在设置页面的导航条右侧---添加一个按钮一键切换内外网
#ifdef DEBUG
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"切服地址" style:UIBarButtonItemStylePlain target:self action:@selector(changeServer)];
#endif
- 在.pch文件添加头文件
#import "ChangeServer.h"
- (void)changeServer {
NSArray *title = @[@"正式",@"测试服",@"本地测试"];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请选择要切换的服务器地址" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
// 遵守协议:UIAlertViewDelegate
alert.delegate = self;
for(NSString* t in title)
{
[alert addButtonWithTitle:t];
}
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex != alertView.cancelButtonIndex) {
[ChangeServer changeServer:(int)buttonIndex-1];
}
}