ios網路編程(二)之網路連接

來源:互聯網
上載者:User

標籤:

 上篇的串連方式皆為同步串連,這次就詳細介紹一下網路連接的方式

 

一、串連方式分兩種:同步和非同步

       同步串連

        1, 使用 [NSURLConnection sendSynchronousRequest:]方法

        2,會出現卡頓現象

       非同步串連分兩種:block 和 delegate 

         1),  block 的使用方法是[NSURLConnection sendAsynchronousRequest:requset queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

    

     }];

      該方法需要兩個參數:request 請求

                       queue 隊列,一般情況是currentQueue

     注意:

       block裡面的代碼不會立即執行,只有當伺服器請求完資料之後才會執行。

  

   2),  delegate的使用方法:

      1,帶delegate的非同步串連將資料下載進度封裝在了協議中,故一般情況下會使用此串連方式

      2, 帶delegate的串連也是非同步串連,介面先出來,之後才擷取到資料,故問題和block一樣

       注意:

         代理中一個名為didReceiveData:方法, 該data不是已經下載的data,需要自己拼接

 

二、同步串連步驟

    NSURL *url = [NSURL URLWithString:網址字串];

    NSURLRequest *requset = [NSURLRequest requestWithURL:url cachePolicy:( NSURLRequestUseProtocolCachePolicy) timeoutInterval:15];

    NSURLResponse *response = nil;

    NSError *error = nil;

    NSData *data = [NSURLConnection sendSynchronousRequest:requset returningResponse:&response error:&error];

  

 

三、非同步串連

 1,block方法

     NSURL *url = [NSURL URLWithString:網址字串];

    NSURLRequest *requset = [NSURLRequest requestWithURL:url cachePolicy:( NSURLRequestUseProtocolCachePolicy) timeoutInterval:15];

    [NSURLConnection sendAsynchronousRequest:requset queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

       // 在此可以解析資料,展示圖片什麼的

    }];

 2, 代理方法

     NSURL *url = [NSURL URLWithString:網址字串];

    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

    [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];

    接受協議後代理方法有 

    接收響應

 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

 

  }

 接收到資料

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{

     

}

// 資料擷取完畢

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{

    

        

}

// 擷取失敗

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{

  

}

 

ios網路編程(二)之網路連接

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.