设为首页 加入收藏

TOP

NSURLConnection同步和异步连接(一)
2015-07-20 18:04:49 来源: 作者: 【 】 浏览:5
Tags:NSURLConnection 同步 异步 连接

NSURLConnection去加载一个URL请求时候有两种方式,一种是同步加载,一种是异步加载。

同步加载会阻塞当前的那个线程,如果将同步加载的代码放在主线程里去执行,那么就会阻塞主线程。

异步加载一种方式使用的是block,就算将加载的代码放到主线程去执行,也不会阻塞主线程。异步加载的另一种方式比较灵活。它可以在你需要的时候去启动,在你不需要的时候可以取消。

\

先看一个在主线程种同步和异步,以及使用GCD同步三种方式加载数据的阻塞情况

//
//  AppDelegate.m
//  NSURLConnectionDemo
//
//  Created by Lion Mac OS on 5/30/14.
//  Copyright (c) 2014 Yi Gui Hua. All rights reserved.
//

#import "AppDelegate.h"

@implementation AppDelegate

- (void)dealloc
{
    [super dealloc];
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
    [self fetchYahooData];
    
    NSLog(@"-------------------------------------");
    [self fetchYahooData2_GCD];
     NSLog(@"-------------------------------------");
    [self fetchYahooData3];
}
//使用异步加载,那么就不会阻塞主线程,因为异步他会开启一个子线程去加载


//不使用GCD,同步加在数据,会阻塞主线程
-(void)fetchYahooData{
    NSLog(@"同步请求测试开始...");
    NSString *urlString = @"http://www.yahoo.com";
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSLog(@"马上进行同步连接请求url的数据");
    NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
    if ([data length] > 0 && error == nil) {
        NSLog(@"%lu 字节的数据被返回.",(unsigned long)[data length]);
    }else if([data length] == 0 && error == nil){
        NSLog(@"没有数据返回");
    }else if (error != nil){
        NSLog(@"出现错误= %@",error);
    }
    NSLog(@"同步方法测试完成."); //它会等待上面的下载数据完成才打印这句话
    
}

//使用GCD,同步加载数据.不会阻塞主线程。
-(void)fetchYahooData2_GCD{
    NSLog(@"使用GCD同步请求测试开始...");
    NSString *urlString = @"http://www.yahoo.com";
    NSLog(@"马上进行同步连接请求url的数据...");
    dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(dispatchQueue, ^{
        NSURL *url = [NSURL URLWithString:urlString];
        NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
        NSURLResponse *response = nil;
        NSError *error = nil;
        NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
        if ([data length] > 0 && error == nil) {
            NSLog(@"%lu 字节的数据被返回.",(unsigned long)[data length]);
//            [data writeToFile:@"/Users/macoslion/Desktop/new/download.html" atomically:YES]; //下载下来的数据保存为xml,或者html。最好是xml
            
        }else if ([data length] == 0 && error == nil){
            NSLog(@"没有数据返回.");
        }else if (error != nil){
            NSLog(@"请求出错 = %@",error);
        }
    });
    NSLog(@"GCD测试完成."); //它会直接打印,不会等到上面下载数据完成才打印
    
}


//使用异步,它也不会阻塞主线程
-(void)fetchYahooData3
{
    NSLog(@"异步请求测试开始..");
    NSString *urlString = @"http://www.yahoo.com";
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];

    NSLog(@"马上进行异步连接请求url的数据...");
    
     
     [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *reponse, NSData *data, NSError *error) {
         if ([data length] > 0 && error == nil) {
             NSLog(@"%lu 字节的数据被返回.",(unsigned long)[data length]);
         }else if([data length] == 0 && error == nil){
             NSLog(@"没有数据返回");
         }else if (error != nil){
             NSLog(@"请求出错 = %@",error);
         }
     }];
   
    NSLog(@"异步方法测试完成"); //这句话不会等到上面打印完了而打印


}
@end


运行结果:

2014-07-22 18:46:03.744 NSURLConnectionDemo[2350:403] 同步请求测试开始...
2014-07-22 18:46:03.857 N
首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇hdu 4869 Turn the pokers(数学) 下一篇iframe笔记及获取根目录的方法

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: