iOS網絡請求http之NSURLConnection簡單異步請求

NSURLConnection對數據的處理方式不同可以分為2種

1、block回調

block一般針對小數據,一次性獲得全部數據并返回。

+ (void)sendAsynchronousRequest:(NSURLRequest*) request

queue:(NSOperationQueue*) queue

completionHandler:(void (^)(NSURLResponse* __nullable response, NSData* __nullable data, NSError* __nullable connectionError)) handler;

這個方法會自動創建一個子線程進行網絡請求,queue一般是mainQueue,請求完成之后在主線程刷新UI。

2、代理

代理通常針對文件下載,會多次調用代理方法。

NSURLConnectionDataDelegate協議中的代理方法

//將要發送請求時調用

- (nullable NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(nullable NSURLResponse *)response;

//開始接收到服務器的響應時調用

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

//接收到服務器返回的數據時調用(服務器返回的數據比較大時會調用多次,一般做大文件下載)

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

//服務器返回的數據完全接收完畢后調用

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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容