24-断点续传-NSURLConnection

//
// ViewController.m
// 03-大文件下载-断点续传
//
// Created by 张旗 on 15/5/19.
// Copyright (c) 2015年 张旗. All rights reserved.
//

#import "ViewController.h"
#import "DACircularProgressView.h"


@interface ViewController ()<NSURLConnectionDataDelegate>

@property (nonatomic, weak) DACircularProgressView *circleView;
@property (nonatomic, assign)long long currentLength;
@property (nonatomic, strong) NSURLConnection *conn;
@property (nonatomic,strong) NSFileHandle *writeHandle;
@property (nonatomic,assign)long long totalLength;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    DACircularProgressView *circleView = [[DACircularProgressView alloc] initWithFrame:CGRectMake(110, 50, 100, 100)];
    circleView.progressTintColor = [UIColor redColor];
    circleView.trackTintColor = [UIColor blueColor];
    circleView.progress = 0.00001;
    [self.view addSubview:circleView];
    self.circleView = circleView;
}

- (IBAction)beginDownload:(UIButton *)button {
    button.selected = !button.selected;

    if (button.selected) {
        // 下载资源的路径
        NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos/test.mp4"];
        NSMutableURLRequest  *request = [NSMutableURLRequest requestWithURL:url];

        // 设置请求头
        NSString *range =[NSString stringWithFormat:@"bytes=%lld-",self.currentLength];
        [request setValue:range forHTTPHeaderField:@"range"];

        self.conn = [NSURLConnection connectionWithRequest:request delegate:self];

    }else{
        NSLog(@"暂停下载");
        [self.conn cancel];
        self.conn = nil;
    }

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - NSURLConnectionDataDelegate协议中的方法

/** * 连接失败的时候调用 * * @param connection <#connection description#> * @param error <#error description#> */
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}

/** * 得到服务器响应的时候调用 * * @param connection <#connection description#> * @param response <#response description#> */
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"得到了服务器端响应");

    if (self.currentLength) return;

    // 文件路径
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filepath = [caches stringByAppendingPathComponent:@"test.zip"];

    // 在沙盒中创建一个文件
    NSFileManager *mgr =[NSFileManager defaultManager];
    [mgr createFileAtPath:filepath contents:nil attributes:nil];

    // 创建一个用来写数据的句柄
    self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:filepath];

    // 获得文件的总大小
    self.totalLength = response.expectedContentLength;
}

/** * 接收服务器端返回的数据 * * @param connection <#connection description#> * @param data <#data description#> */
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"接收数据");
    // 写的文件句柄移动到文件的最末尾
    [self.writeHandle seekToEndOfFile];
    // 将数据写入沙盒
    [self.writeHandle writeData:data];
    // 累计文件的长度
    self.currentLength += data.length;
    self.circleView.progress = (double)self.currentLength / self.totalLength;
}

/** * 下载完成 * * @param connection <#connection description#> */
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"下载完成");
    self.currentLength = 0;
    self.totalLength = 0;
    // 关闭文件
    [self.writeHandle closeFile];
    self.writeHandle = nil;
}
@end

你可能感兴趣的:(24-断点续传-NSURLConnection)