标签:unsigned hand def 数据 async length 网络 void sop
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// [self getYahooData];//同步请求,会阻塞主线程
// [self getYahooData_GCD];//使用GCD把同步请求放在子线程中,也不会阻塞主线程
[self getYahooData_Async];//直接使用异步请求,不会阻塞主线程+
}
-(void)getYahooData_Async
{
NSLog(@"异步请求测试开始...");
NSURL *url = [NSURL URLWithString:@"http://www.yahoo.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSLog(@"马上进行异步连接请求url的数据");
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (data.length > 0 && connectionError == nil) {
NSLog(@"%lu字节的数据被返回",(unsigned long)data.length);
}else if (connectionError == nil && data.length == 0)
{
NSLog(@"没有数据返回。。");
}else if (connectionError != nil)
{
NSLog(@"返回错误");
}
}];
NSLog(@"异步请求测试完成。。");
}
-(void)getYahooData_GCD
{
NSLog(@"异步请求测试开始...");
NSURL *url = [NSURL URLWithString:@"http://www.yahoo.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSLog(@"马上进行异步连接请求url的数据");
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (data.length > 0 && error == nil) {
NSLog(@"%lu字节的数据被返回",(unsigned long)data.length);
}else if (error == nil && data.length == 0)
{
NSLog(@"没有数据返回。。");
}else if (error != nil)
{
NSLog(@"返回错误");
}
});
NSLog(@"GCD测试完成。。");
}
-(void)getYahooData
{//同步请求,会阻塞主线程
NSLog(@"同步请求测试开始...");
NSURL *url = [NSURL URLWithString:@"http://www.yahoo.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response = nil;
NSError *error = nil;
NSLog(@"马上进行同步连接请求url的数据");
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (data.length > 0 && error == nil) {
NSLog(@"%lu字节的数据被返回",(unsigned long)data.length);
}else if (error == nil && data.length == 0)
{
NSLog(@"没有数据返回。。");
}else if (error != nil)
{
NSLog(@"返回错误");
}
NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}
标签:unsigned hand def 数据 async length 网络 void sop
原文地址:https://www.cnblogs.com/dashengios/p/10536322.html