IOS 练习 之简单的文件下载

//
//  ViewController.m
//  DownLoadBig
//
// 添加alertview并打印文件大小
// Storyboard添加progressview 
// 文件的大小可以从request中取出,也可以使用
// self.total = res.expectedContentLength
//
//  Created by apple on 15/5/5.
//  Copyright (c) 2015年 apple. All rights reserved.
//
#import "ViewController.h"
@interface ViewController () <NSURLConnectionDataDelegate,UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UIProgressView *proView;
@property (nonatomic,strong) NSMutableData *fileData;
@property (nonatomic,copy) NSString *total;
@property (nonatomic,strong) UIAlertView *alert;
@end
@implementation ViewController
-(NSMutableData *)fileData
{
    
    if (_fileData == nil){
        
        _fileData = [NSMutableData data];
    }
    return _fileData;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.proView.progress = 0.0;
    
   
    // Do any additional setup after loading the view, typically from a nib.
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    NSURL *url = [NSURL URLWithString:@"http://125.39.68.200/files/2011000000F9723B/xiazai.888rj.com/Soft/T/Thunder_7.9.26.4824_XiaZaiBa.exe"];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection connectionWithRequest:req delegate:self];
//    NSLog(@"touch");
    
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;
//    NSLog(@"jieshou");
//    NSLog(@"%@%",res.allHeaderFields[@"Content-Length"]);
     self.total= res.allHeaderFields[@"Content-Length"];
          
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    
    [self.fileData appendData:data];
    
    self.proView.progress = (double)self.fileData.length  / self.total.intValue;
    NSLog(@"%d%",self.fileData.length);
    
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *cachestr = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [cachestr stringByAppendingPathComponent:@"Thunder_7.9.26.4824_XiaZaiBa.exe"];
    NSLog(@"%@",cachestr);
    
    [self.fileData writeToFile:filePath atomically:YES];
    
    NSString *totalstr = [ NSString stringWithFormat:@"软件总大小:%@",self.total];
    self.alert = [[UIAlertView alloc]  initWithTitle:@"下载完成" message:totalstr delegate:self cancelButtonTitle:@"ok"  otherButtonTitles: nil ];
    
    [self.alert show];
}
@end

你可能感兴趣的:(IOS 练习 之简单的文件下载)