NSData *getData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
// 此同步请求方法在9.0之后提示以废弃,建议使用 NSURLSession 的方法
NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
// 此方法解析数据是在子线程中执行的,等同于异步请求了。页面加载完成才能获取到数据
}];怎样使用 NSURLSession 进行同步请求,可在下面直接调用请求下来的数据,而不是回到主线程刷新页面的数据源、求各路大神帮忙~
// 此同步请求方法在9.0之后提示以废弃,建议使用 NSURLSession 的方法
NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
// 此方法解析数据是在子线程中执行的,等同于异步请求了。页面加载完成才能获取到数据
}];怎样使用 NSURLSession 进行同步请求,可在下面直接调用请求下来的数据,而不是回到主线程刷新页面的数据源、求各路大神帮忙~
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:1];
AFHTTPRequestOperation *operstion = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
[operstion start];
[operstion waitUntilFinished];
return operstion.responseData;贴一段 AF 的代码自己看吧。
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
dispatch_semaphore_t disp = dispatch_semaphore_create(0);
NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//处理model
dispatch_semaphore_signal(disp);
}];
[dataTask resume];
dispatch_semaphore_wait(disp, DISPATCH_TIME_FOREVER);
var data: NSData? = nil
let semaphore: dispatch_semaphore_t = dispatch_semaphore_create(0)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {
taskData, _, error -> () in
data = taskData
if data == nil, let error = error {print(error)}
dispatch_semaphore_signal(semaphore);
})
task.resume()
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
return data
}