在创建一个同步的网链接的时候我们需要明白一点,并不是我们的这个同步连接一定会堵塞我们的主线程,如果这个同步的链接是创建在主线程上的,那么这种情况下是会堵塞我们的主线程的。其他情况下是不一定会堵塞我们的主线程的。
这个例子中,我们将会尝试取回Yahoo主页的内容:
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions{
NSLog(@"We are here ... ");
NSString *urlAsString = @"";
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSURLResponse *response = nil;
NSError *error = nil;
NSLog(@"Firing synchronous url connection...");
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&responseerror:&error];
if([data length]>0 && error == nil){
NSLog(@"%lu bytes of data was returned.",(unsigned long)[data length]);
}else if ([data length] == 0 && error == nil){
NSLog(@"No data was returned.");
}else if (error != ni){
NSLog(@"Error happened = %@",error);
NSLog(@"We are done.");
}
self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
打印效果:
We are here...
Firing synchronous url connection... 194472 bytes of data was returned. We are done.
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions{
NSLog(@"We are here ... ");
NSString *urlAsString = @"";
NSLog(@"Firing synchronous url connection...");
dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_PRIORITY_DEFAULT, 0);
dispatch_async(dispatchQueue, ^(void){
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequestreturningResponse:&response error:&error];
if([data length]>0 && error == nil){
NSLog(@"%lu bytes of data was returned.",(unsigned long)[data length]);
}else if ([data length] == 0 && error == nil){
NSLog(@"No data was returned.");
}else if (error != ni){
NSLog(@"Error happened = %@",error);
}
});
NSLog(@"We are done.");
self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
打印效果:
We are here...
Firing synchronous url connection... We are done.
194326 bytes of data was returned.
看了如上的代码是不是感觉特别奇怪,怎么 we are done 还是放在最后面的,怎么现在打印到前面的了,这 就是我们要证明的,其实同步的程序并不一定会堵塞我们的主线程的。只要我们的这个同步的线程并不是建立 在我们的主线程上的,如果我们把他添加到 GCD 队列池中的话,那么我们的主线程也就没有被堵塞。这样同 步的概念实际上也可以看做是某种程度上的异步。
通过NSMutableURLRequest包装URL的请求形式
你想在传给一个请求链接前能适应一个URL的不同HTTP头及其设置。
通过NSMutableURLRequest代替NSURLRequest