iOS网络: NSURLConnection进行同步下载

  通过 NSURLConnection 的 sendSynchronousRequest:returningResponse:error: 方法创建一 个同步的网络连接。这个方法将会返回一个 NSData 类型的数据 
 
  在创建一个同步的网络连接的时候我们需要明白一点,并不是是我们 的这个同步连接一定会堵塞我们的主线程,如果这个同步的连接是创建在主线程上的,那么 这种情况下是会堵塞我们的主线程的,其他的情况下是不一定会堵塞我们的主线程的。如果你在 GCD 的全局并发队列上初始化了一个同步的连接,你其实并不会堵塞我们的主线程的。 

 

例子:

- (void)sendSynNetwork{
    NSLog(@"Wo are here...");
    NSString *urlString = @"http://www.baudu.com";
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
    //同步没有block
    //这样解决比较方便
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSLog(@"开始同步请求");
    NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&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 != nil){
        NSLog(@"Error happened = %@", error);
    }
    NSLog(@"We are done.");
}

Wo are here...

开始同步请求

8875 bytes of data was returned.

We are done.

 
通过上面的代码我们不难发现,其实我们的主线程是一直堵塞着,也就是说段代码是一行一行执行的。
 
下面让我们看一下,当我们创建一个同步的连接,并且添加到 GCD 的队列池中去,我们又会发现什么: 

 

//简单的同步请求
- (void)sendSynNetwork{
    NSLog(@"Wo are here...");
    NSString *urlString = @"http://www.baudu.com";
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
    dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(dispatchQueue, ^{
        //同步没有block

        //这样解决比较方便
        NSURLResponse *response = nil;
        NSError *error = nil;
        NSLog(@"开始同步请求");
        NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&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 != nil){
            NSLog(@"Error happened = %@", error);
        }
        
    });
   NSLog(@"We are done.");
}

Wo are here...

We are done.

开始同步请求

9138 bytes of data was returned.

 

 

 

 

posted @ 2014-11-11 11:57  safiri  阅读(383)  评论(0编辑  收藏  举报