1.建立 DataSource : NSObject 文件 這個(gè)文件是數(shù)據(jù)最底層, 是對(duì)AFN 等請(qǐng)求庫的封裝和后臺(tái)接口的解析(在DataSource中Block回調(diào)的數(shù)據(jù)是最外層的)蜕企。
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];//對(duì)錯(cuò)誤信息的處理
}];
}
在外邊Module: NSObject 中會(huì)對(duì)dataSource中回調(diào)回的數(shù)據(jù)進(jìn)行具體細(xì)化處理但指,這個(gè)文件中的block方法是外面調(diào)用的掂为,大部分會(huì)在View中調(diào)用,屬于MVVM模式洼畅。