在请求网络数据的时候,我们通常做法让一个单例单独来负责数据的发送和传输。
这里记录下参数为block的回调方式吧。
例子:在单例中,.h
- (void)loginName:(NSString *)name
pwd:(NSString *)pwd
success:(void(^)(NSError * error,SDataHelper *result,SLoginHelper *helper))success
failure:(void(^)(NSError * error,SDataHelper *result))failure;
.m
- (void)loginName:(NSString *)name
pwd:(NSString *)pwd
success:(void(^)(NSError * error,SDataHelper *result,SLoginHelper *helper))success
failure:(void(^)(NSError * error,SDataHelper *result))failure{
//将name和pwd发送到服务器端拿到反馈值,此处省略部分代码
NSString *str = [NSString stringWithFormat:@"%@?%@",url,parmastring];
NSString *urlstring = [NSString stringWithFormat:@"%@%@?%@",main_url,url,parmastring];
NSURL *urld = [NSURL URLWithString:urlstring];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:urld];
[request addRequestHeader:@"User-Agent" value:app_version];
[request addRequestHeader:@"OSVerSion" value:@"CommonServer"];
[request addRequestHeader:@"MacAddress" value:[NSString macAddress]];
[request addRequestHeader:@"Hash" value:[self hashWithUrlArguments:str]];
[request setRequestMethod:@"GET"];
[request setTimeOutSeconds:30];
__block typeof(request) weakFuck = request;
[request setCompletionBlock:^{
NSDictionary *dic = [self dictionarayWithJsonString:weakFuck.responseString];
SDataHelper *helper = [[SDataHelper alloc] init];
[helper wSetModelWithDic:dic TypeIsJsonNoDb:YES];
SLoginHelper *Lhelper = [[SLoginHelper alloc] init];
[Lhelper wSetModelWithDic:dic TypeIsJsonNoDb:YES];
if (helper.status == 0) {
success (nil,helper,Lhelper); //此处是回调,是在以上request 取得数值后,回到调用loginName:pwd:success:failure:这个函数的地方去执行block方法
} else {
failure (nil,helper);
}
}];
[request startAsynchronous];
}
调用方法:
[xxx loginName:(NSString *)name
pwd:(NSString *)pwd
success:^(NSError * error,SDataHelper *result,SLoginHelper *helper){
//这就是登录取得数据后,以上三个参数都是从上面那个类里传过来的参数,在这里进行后续处理
}
failure:^(NSError * error,SDataHelper *result){
}];