NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:@“url”];
NSURLResponse *response= nil;
// 4 创建连接对象(同步)
NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSURLConnection iOS 9.0已经废弃,使用NSURLSession+dispatch_semaphore_t 完成同步请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:@“url”];
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
NSURLSessionDataTask*dataTask= [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//线程中
dispatch_semaphore_signal(semaphore);
}];
[dataTask resume];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);