iOS网络下载三函数NSURLConnection/NSURLRequest/NSMutableData

原生的NSURL同步下载,并且调用三个函数   RootViewController.h中定义

NSURLConnection * myConnection;//连接网络    
NSMutableData *allData;//存储网络下载的数据   
其中:

1
2
3
4
5
6
7
8
9
- (void)viewDidLoad {    
    [superviewDidLoad];     
    NSString *urlString=@"http://www.baidu.com/img/baidu_jgylogo3.gif";
    NSURL * url = [NSURLURLWithString:urlString];     
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];//通过url,获得request;
    myConnection = [[NSURLConnection alloc] initWithRequest:request
    delegate:self];//根据request得到connection;     
    [request release]; 
}

网络三个函数

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//下载完成,可以对一些数据进行处理,如在这里就用data得到图片;
- (void)connectionDidFinishLoading:(NSURLConnection*)connection[myConnection release];    
    NSString * string = [[NSStringalloc] initWithData:allDataencoding:NSUTF8StringEncoding];
    NSLog(@"string ------------------- > %@",string);
    NSLog(@"function %s is calling",__func__);//获得方法名称
    UIImage *img =[UIImageimageWithData:allData];
    CGRect imageframe = CGRectMake(0, 0, img.size.width, img.size.height);
    UIImageView * imageview = [[UIImageViewalloc] initWithFrame:imageframe];
    [imageview setImage:img];
    [self.viewaddSubview:imageview];
    [imageview release];
    [string release];
    [allDatarelease];//每接收一段数据就会调用此函数
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {         
    [allDataappendData:data];//data加到allData最后 
}
//接收完HTTP协议头,开始真正接手数据时候调用 
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    allData = [[NSMutableDataalloc] initWithLength:0];    
    // NSLog(@"function %s is calling",__func__);     
    NSHTTPURLResponse * res = (NSHTTPURLResponse *)response;     
    NSInteger statusCode = [res statusCode];     
    if(statusCode >= 400)     {         
        NSLog(@"HTTP ERROR CODE %d",statusCode);     
    }     
    NSDictionary * dic = [res allHeaderFields];     
    NSLog(@"all Header Field %@",dic); 
}

你可能感兴趣的:(iOS网络下载三函数NSURLConnection/NSURLRequest/NSMutableData)