JSONasynchronous请求

我想使用asynchronous请求获取JSON数据,我正在通过syncrouns这样做,但现在需求是变化,但我无法修改此代码为asynchronous,因为我必须返回NSdata

+ (NSString *)stringWithUrl:(NSURL *)url { // if(kShowLog) NSLog(@"%@", url); NSURL *newURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@",url]]; NSURLRequest *urlRequest = [NSURLRequest requestWithURL:newURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:1]; // Fetch the JSON response NSData *urlData; NSURLResponse *response; NSError *error; // NSOperationQueue *opQueue; // Make synchronous request urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error]; return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding]; } 

如果要保持返回数据,请在2.线程上调用stringWithUrl。 (我会去asynchronous数据

 dispatch_async(dispatch_get_global_queue(), ^{ NSData *d = [self stringWithUrl:myURL]; ... //update ui dispatch_sync(dispatch_get_main_queue(), ^{ ... }); }); 

一种可以工作的方式,但是QUITE的破解(在苹果机上的旧版API中一直使用的苹果)将在等待的时候运行runloop:

hackisch ::但是在给定完成块运行在同一个线程上然后runloop的情况下包装asynchronous同步

  __block NSString *responseString = nil; [NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:myurl] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { responseString = [[NSString alloc] initWithData:Data encoding:NSUTF8StringEncoding]; if(!responseString) { responseString = @""; } }]; while(!responseString) { [NSRunloop currentRunloop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]; } return responseString; 

你必须为这个进程创build一个单独的线程,获取json数据的同步调用将阻塞你的主线程。

我正在改变你的代码做asynchronous操作从Web服务获取JSON数据。

 + (void)stringWithUrl:(NSURL *)url { dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); dispatch_async(queue, ^{ // if(kShowLog) NSLog(@"%@", url); NSURL *newURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@",url]]; NSURLRequest *urlRequest = [NSURLRequest requestWithURL:newURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:1]; // Fetch the JSON response NSData *urlData; NSURLResponse *response; NSError *error; // NSOperationQueue *opQueue; // Make synchronous request urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error]; dispatch_sync(dispatch_get_main_queue(), ^{ //Here you have to put your code, which you wanted to get executed after your data successfully retrived. //This block will get executed after your request data load to urlData. }); }); } 

那么asynchronous怎么了呢,

  NSString *responseString; NSOperationQueue *operation = [[NSOperationQueue alloc]init]; [NSURLConnection sendAsynchronousRequest:request queue:operation completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSLog(@"data %@", data); responseString = [[NSString alloc] initWithData:Data encoding:NSUTF8StringEncoding]; }]; return responseString;