#import "ViewController.h"
@interface ViewController ()<NSURLConnectionDataDelegate,NSURLConnectionDelegate>
{
NSURL *_url;
NSURLConnection *_connection;
//文件读写
NSFileHandle *_fileHandle;
//下载文件保存路径
NSString *_filePath;
//文件真实大小
long long _expectSize;
//已经下载的大小
long long _readSize;
}
@property (weak, nonatomic) IBOutlet UILabel *progressLabel;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@property (weak, nonatomic) IBOutlet UIButton *startBtn;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"%@",NSHomeDirectory());
// NSLog(@"%@",[NSURL URLWithString:[@"http://127.0.0.1/掌厨项目.zip" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]);
_url = [NSURL URLWithString:[@"http://127.0.0.1/1.zip" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}
- (IBAction)download:(UIButton *)sender {
if ([sender.titleLabel.text isEqualToString:@"开始下载"]) {
[sender setTitle:@"暂停" forState:UIControlStateNormal];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_url];
NSString *range = [NSString stringWithFormat:@"bytes=%lld-",_readSize];
[request setValue:range forHTTPHeaderField:@"range"];
_connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
}
else
{
[sender setTitle:@"开始下载" forState:UIControlStateNormal];
[_connection cancel];
}
}
#pragma mark - ConnectionDelegate
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"%@",error.localizedDescription);
}
//接收到服务端响应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
if (!_expectSize) {
//获取文件真实大小
_expectSize = response.expectedContentLength;
_filePath = [NSHomeDirectory() stringByAppendingString:@"/Library/Caches/1.zip"];
NSFileManager *manager = [NSFileManager defaultManager];
[manager createFileAtPath:_filePath contents:nil attributes:nil];
_fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:_filePath];
}
}
//接收到服务端数据(数据量大时,会调用多次)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//获取到已经下载的大小
_readSize += data.length;
// data writeToFile:<#(NSString *)#> atomically:<#(BOOL)#>
[_fileHandle seekToEndOfFile];
[_fileHandle writeData:data];
CGFloat ratio = 1.0*_readSize/_expectSize;
_progressLabel.text = [NSString stringWithFormat:@"%.f%%",ratio*100];
_progressView.progress = ratio;
}
//下载完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"下载完成!");
[_fileHandle closeFile];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end