iOS NSURLConnection和非同步網路請求

來源:互聯網
上載者:User

標籤:style   blog   class   code   java   tar   

在日常應用中,我們往往使用AFNetworking等第三方庫來實現網路請求部分。這篇文章會簡要地介紹一下如何使用NSURLConnection來進行非同步網路請求。

我們先看一個小demo

- (void)viewDidLoad{    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.        NSString *urlStr = @"http://www.baidu.com";    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];        //從這個實驗可以看出,connection的函數在 mainrunloop運行for迴圈時根本無法被調用,由此可見,這裡的connection是在mainThread中啟動並執行。    NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:request delegate:self];        for(int i = 0 ;i<10000;i++)    {        NSLog(@"%d",i);    }        NSLog(@"for end==========");}- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{    NSLog(@"good!!!!!!!!");}

看下輸入

2014-05-05 10:34:18.861 UrlConnectionASyncTest[9988:60b] 99972014-05-05 10:34:18.862 UrlConnectionASyncTest[9988:60b] 99982014-05-05 10:34:18.862 UrlConnectionASyncTest[9988:60b] 99992014-05-05 10:34:18.862 UrlConnectionASyncTest[9988:60b] for end==========2014-05-05 10:34:18.865 UrlConnectionASyncTest[9988:60b] good!!!!!!!!

查看蘋果的文檔會發現如下的解釋

By default, a connection is scheduled on the current thread in the default mode when it is created. If you create a connection with the initWithRequest:delegate:startImmediately: method and provide NO for the startImmediately parameter, you can instead schedule the connection on an operation queue before starting it with the start method.You cannot reschedule a connection after it has started.

這就是說,如果你僅僅通過在主線程中使用initWithRequest:delegate:方法建立一個connection對象,它會預設地加入到mainThread中,這樣當資料返回時,會在main thread中執行,這就會影響UI的重新整理。這種connnection不是同步的connection,因為它在沒有得到資料時就可以繼續執行其他代碼,但也不是那種真正的非同步connection,因為它的回呼函數會在main thread中執行,會影響main thread中的其他函數執行。

那麼如何建立一個在其他thread中執行回呼函數的connection呢?系統提供了2套方法,

第一套是使用類方法,sendAsynchronousRequest:queue:completionHandler:

第二套是使用幾個對象方法,順序如下

1.使用initWithRequest:delegate:startImmediately:產生一個不立即開始的connnection2.通過scheduleInRunLoop:forMode: 或者 setDelegateQueue: 設定回調方法啟動並執行thread,推薦使用第二個。3.調用start開始connection請求。

下面給出一個demo

- (void)viewDidLoad{    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.        NSString *urlStr = @"http://www.baidu.com";    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];    //從這個實驗可以看出,connection的函數在 mainrunloop運行for迴圈時根本無法被調用,由此可見,這裡的connection是在mainThread中啟動並執行。    // NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:request delegate:self];    NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];    [con setDelegateQueue:[[NSOperationQueue alloc] init]];    [con start];        for(int i = 0 ;i<10000;i++)    {        NSLog(@"%d",i);    }        NSLog(@"for end==========");}- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{  //  NSLog(@"data is %@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);    NSLog(@"good!!!!!!!!");}

結果如下

2014-05-05 11:23:15.129 UrlConnectionASyncTest[10147:60b] 3442014-05-05 11:23:15.129 UrlConnectionASyncTest[10147:60b] 3452014-05-05 11:23:15.129 UrlConnectionASyncTest[10147:60b] 3462014-05-05 11:23:15.129 UrlConnectionASyncTest[10147:60b] 3472014-05-05 11:23:15.129 UrlConnectionASyncTest[10147:60b] 3482014-05-05 11:23:15.129 UrlConnectionASyncTest[10147:60b] 3492014-05-05 11:23:15.130 UrlConnectionASyncTest[10147:60b] 3502014-05-05 11:23:15.134 UrlConnectionASyncTest[10147:4207] good!!!!!!!!2014-05-05 11:23:15.143 UrlConnectionASyncTest[10147:60b] 3512014-05-05 11:23:15.144 UrlConnectionASyncTest[10147:60b] 3522014-05-05 11:23:15.144 UrlConnectionASyncTest[10147:4207] good!!!!!!!!2014-05-05 11:23:15.144 UrlConnectionASyncTest[10147:60b] 3532014-05-05 11:23:15.144 UrlConnectionASyncTest[10147:60b] 3542014-05-05 11:23:15.144 UrlConnectionASyncTest[10147:60b] 3552014-05-05 11:23:15.145 UrlConnectionASyncTest[10147:60b] 356

可以看出connection的回呼函數已經不再main thread中執行了!

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.