Objective-c 网络编程1 Web请求和响应

//
//  ViewController.m
//  网络编程
//
//  Created by DC017 on 15/12/9.
//  Copyright © 2015年 DC017. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<NSURLConnectionDataDelegate>
{
    UITextField *textfield;
    UILabel* label;
    UIButton *button;
    UIProgressView *progress;
    NSMutableData * mudata;
    long long totalLength;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
   

    [self buju];
    
}
-(void)buju{
    
    
    textfield =[[UITextField alloc]initWithFrame:CGRectMake(10, 60, 300, 30)];
    textfield.layer.borderWidth=2;
    textfield.layer.cornerRadius=7;
    textfield.text=@"http://b.zol-img.com.cn/desk/bizhi/image/7/1920x1080/1449126103556.jpg";
    textfield.layer.borderColor=[UIColor blackColor].CGColor;
    [self.view addSubview:textfield];
    
   progress=[[UIProgressView alloc]initWithFrame:CGRectMake(10, 100, 300,2 )];
   progress.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:progress];
    
    label =[[UILabel alloc]initWithFrame:CGRectMake(10, 130, 100, 20)];
    label.textColor=[UIColor blackColor];
    label.text=@"请下载";
    
    [self.view addSubview:label];
    
     button=[[UIButton alloc]initWithFrame:
    CGRectMake(40, 400, 50, 20)];
    
    [button setTitle:@"下载" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    button.layer.borderWidth=1;
    button.layer.borderColor=[UIColor redColor].CGColor;
    button.layer.cornerRadius=8;
    [self.view addSubview:button];
    
    [button addTarget:self action:@selector(xiazai) forControlEvents:UIControlEventTouchUpInside];
    
    
    
}

-(void)xiazai{
    NSLog(@"下载");
    NSString * tri=textfield.text;
    //新版
    //tri=[tri stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    
    //旧版
    tri=[tri stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url=[NSURL URLWithString:tri];
    
    //创建请求
    NSURLRequest *request=[[NSURLRequest alloc]initWithURL:url cachePolicy:0 timeoutInterval:15.0f];
    
    //创建连接
    NSURLConnection * Connection=[[NSURLConnection alloc]initWithRequest:request delegate:self];
    
    //启动连接
    [Connection start];

}
#pragma mark -开始代理 的四种方法

#pragma mark 开始接收响应
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSLog(@"接收响应");
    mudata=[[NSMutableData alloc]init];
    //初始化进度条
    progress.progress=0;
    NSLog(@"%@",response);
    
    //处理响应;
    //通过响应头中
    
    NSHTTPURLResponse * httpurl=(NSHTTPURLResponse *)response;
    NSDictionary * head=[httpurl allHeaderFields];
    NSLog(@"%@",head);
    
    totalLength =[head [@"Content-Length"]longLongValue];
    
    NSLog(@"%lld",totalLength);
    
    
}
#pragma mark 接收数据
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    NSLog(@"接收数据");
    
    [mudata appendData:data];
    //更新进度条
    
    [self gengxinjindutiao];
    
    
}
#pragma mark 数据接收完成
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"数据接收完成");
    //数据保存苹果官方要求只能保存到缓存里
    NSString *path=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    
    NSLog(@"%@",path);
    path=[path stringByAppendingPathComponent:@"下载图片01.jpg"];
    //保存下载内容
    [mudata writeToFile:path atomically:YES];
    
}

#pragma mark 请求数据失败
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"请求失败 原因是:%@",error);
}

-(void)gengxinjindutiao{
    if (mudata.length==totalLength) {
        label.text=@"下载完成";
    }
    else{
        label.text=@"正在下载";
        
    }
    progress.progress=(float)mudata.length/totalLength;
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


你可能感兴趣的:(Objective-c 网络编程1 Web请求和响应)