IOS 網路淺析-(三 NSURLConnection代理),iosnsurlconnection
對於現在的iOS開發,用法簡單,最古老最經典最直接的NSURLConnection的作用不是很大,但是作為一名ios開發人員,我們應該擁有一顆熱愛學習的心,下面通過代碼的實現簡單介紹一下NSURLConnection。
//// ViewController.m// CX- NSURLConnection//// Created by ma c on 16/3/17.// Copyright © 2016年 xubaoaichiyu. All rights reserved.//#import "ViewController.h"@interface ViewController ()<NSURLConnectionDataDelegate>@property (nonatomic, strong) NSMutableData * data;@end@implementation ViewController#pragma mark - life- (void)viewDidLoad { [super viewDidLoad]; //data初始化,這個很簡單,但是如果粗心大意很容易造成不必要的煩惱 self.data = [NSMutableData data]; NSString * urlString = [NSString stringWithFormat:@"http://localhost/tupian.jpg"]; //如果有中文,則不能正常運行,因此在這裡進行處理。 //注意設定 ios為8 以下 urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL * url = [NSURL URLWithString:urlString]; NSURLRequest * request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15]; NSURLConnection * connection = [NSURLConnection connectionWithRequest:request delegate:self]; //開啟網路 [connection start]; }#pragma mark - deleDate//伺服器返回訊息-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ NSLog(@"伺服器返回訊息");}//接受資料(多次調用)-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ [self.data appendData:data]; }//請求完成-(void)connectionDidFinishLoading:(NSURLConnection *)connection{ NSLog(@"%@",self.data); NSLog(@"請求完成");}//有序二進位代碼過長,截取部分結果。/* 2016-03-17 21:15:15.699 CX- NSURLConnection[3175:173721] 伺服器返回訊息 2016-03-17 21:15:15.702 CX- NSURLConnection[3175:173721] <ffd8ffe0 00104a46 49460001 01000048 00480000 ffe10058 45786966 00004d4d 002a0000 00080002 01120003 00000001 00010000 87690004 00000001 00000026 00000000 0003a001 00030000 00010001 0000a002 00040000 00010000 02eea003 00040000 00010000 a6845cde 3af7a697 f4aaead9 c8a70cd5 08ffd9> 2016-03-17 21:15:15.788 CX- NSURLConnection[3175:173721] 請求完成 */@end