我有一个单例类,我已经实现了一个通过URL解析json数据的方法。代码如下
-(id)parseJsonDataWIthURL:(NSString *)url :(NSString*)datumm
{
NSMutableDictionary *arrrrr=[[NSMutableDictionary alloc]init];
NSMutableURLRequest *reqqq=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:url]];
NSData *dataaa=[datumm dataUsingEncoding:NSUTF8StringEncoding];
[reqqq setHTTPMethod:@"POST"];
[reqqq setHTTPBody:dataaa];
NSURLSessionConfiguration *configg=[NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession*sessionn=[NSURLSession sessionWithConfiguration:configg delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDataTask *taskk=[sessionn dataTaskWithRequest:reqqq completionHandler:^(NSData *data,NSURLResponse *responce,NSError *error){
if(error)
{
NSLog(@"%@", [error localizedDescription]);
}else{
NSMutableDictionary *d = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments|NSJSONReadingMutableContainers error:&error];
NSLog(@"data %@",d);
[arrrrr setDictionary:d];
}
}];
[taskk resume];
return arrrrr;
}
该方法不返回任何值,这是因为块在该方法中执行时需要时间才能返回结果。那么有没有办法等到块完成并返回值。
答案 0 :(得分:0)
ragul ml,
我建议的最简单的解决方案是使用块:)
以下是如何实现它:)将-(id)parseJsonDataWIthURL:(NSString *)url :(NSString*)datumm
修改为,
-(void)parseJsonDataWIthURL:(NSString *)url :(NSString*)datumm withCompletionBlock:(void(^)(NSMutableArray *))completionBlock
{
NSMutableDictionary *arrrrr=[[NSMutableDictionary alloc]init];
NSMutableURLRequest *reqqq=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:url]];
NSData *dataaa=[datumm dataUsingEncoding:NSUTF8StringEncoding];
[reqqq setHTTPMethod:@"POST"];
[reqqq setHTTPBody:dataaa];
NSURLSessionConfiguration *configg=[NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession*sessionn=[NSURLSession sessionWithConfiguration:configg delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDataTask *taskk=[sessionn dataTaskWithRequest:reqqq completionHandler:^(NSData *data,NSURLResponse *responce,NSError *error){
if(error)
{
NSLog(@"%@", [error localizedDescription]);
completionBlock(nil)
}else{
NSMutableDictionary *d = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments|NSJSONReadingMutableContainers error:&error];
NSLog(@"data %@",d);
[arrrrr setDictionary:d];
if (completionBlock) {
completionBlock(arrrrr);
}
}
}];
[taskk resume];
}
最后修改你的电话,
[[YourSingletonClass sharedInstance] parseJsonDataWIthURL:your_url :datumm withCompletionBlock:^(NSMutableArray *array) {
if (array){
//web service is successful
}
}];