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;