1.建立 DataSource : NSObject 文件 这个文件是数据最底层, 是对AFN 等请求库的封装和后台接口的解析(在DataSource中Block回调的数据是最外层的)。
DataSource.h
+ (DataSource *)sharedInstance;
- (void)bulletinListFromOffset:(NSInteger)offset success:(void (^)(NSDictionary *))success failure:(void (^)(NSInteger))failure;
DataSource.m
#pragma mark - Singleton -
+ (DataSource *)sharedInstance {
@synchronized(self) {
if (s_sharedInstance == nil) {
s_sharedInstance = [[self alloc] init];
}
}
return s_sharedInstance;
}
#pragma mark - Init -
- (id)init {
self = [super init];
if (self) {
m_netClient = [[NetClient alloc] initWithBaseURL:[NSURL URLWithString:SERVER_BASE_URL]];//NetClient继承自AFN;
m_netClient.requestSerializer = [AFJSONRequestSerializer serializer];
m_errorHandler = [[NetErrorHandler alloc] init];
_isLogin = NO;
}
return self;
}
#pragma mark - Bulletin -
- (void)bulletinListFromOffset:(NSInteger)offset success:(void (^)(NSDictionary *))success failure:(void (^)(NSInteger))failure {
NSDictionary *params = @{@"offset": [NSString stringWithFormat:@"%ld", (long)offset]};
NSString *urlString = @"接口";
[self getRequestWithURL:urlString params:params success:success failure:failure];
}
#pragma mark - Private Methods -
- (void)getRequestWithURL:(NSString *)url params:(id)params success:(void (^)(NSDictionary *))success failure:(void (^)(NSInteger))failure {
m_netClient.responseSerializer = [AFJSONResponseSerializer serializer];
[m_netClient GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary* response = (NSDictionary *)responseObject;
if (success != nil) {
success(response);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSDictionary* response = (NSDictionary *)operation.responseObject;
NSInteger errorCode = [[response objectForKey:ERROR_CODE_KEY] integerValue];
NSString* errorMessage = [response objectForKey:ERROR_MESSAGE];
[self handleError:errorCode message:errorMessage failure:failure];//对错误信息的处理
}];
}
在外边Module: NSObject 中会对dataSource中回调回的数据进行具体细化处理,这个文件中的block方法是外面调用的,大部分会在View中调用,属于MVVM模式。