使用NSURLSession同步获取数据(通过添加信号量)

//创建NSURL对象

NSURL *url = [NSURL URLWithString:@""]]; 

//创建请求对象

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@""]];

__block NSData *responseData = nil;    

__block NSError *responseError = nil;

NSURLSession *session = [NSURLSession sharedSession];

dispatch_semaphore_t semaphore= dispatch_semaphore_create(0);

NSURLSessionDataTask *task = [session dataTaskWithRequest:request

completionHandler:

^(NSData *data, NSURLResponse *response, NSError *error) {

// ...

responseData = data;

responseError = error;

NSLog(@"-----%@",response);

dispatch_semaphore_signal(semaphore);

}];

[task resume];

dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

你可能感兴趣的:(使用NSURLSession同步获取数据(通过添加信号量))