iOS断点续传

来源:互联网 发布:msp430单片机自学笔记 编辑:程序博客网 时间:2024/05/19 11:35

#import "ViewController.h"



@interface ViewController ()<NSURLConnectionDataDelegate>


@property (nonatomic,strong)UIProgressView *progressView;


@property (nonatomic,strong)UILabel *progressLabel;


@property (nonatomic,strong)UIButton *startButton;


@property (nonatomic,strong)UIButton *stopButton;


//临时文件,存储当前下载多少数据

@property (nonatomic,copy)NSString *tempFilePath;

//更新文件数据的助手

@property (nonatomic,strong)NSFileHandle *fileHand;

//记录临时文件的数据大小

@property (nonatomic,assign)unsigned longlong tempFileSize;

//记录总数据的大小

@property (nonatomic,assign)unsigned longlong fullFileSize;

//记录当前数据的大小

@property (nonatomic,assign)unsigned longlong currentSize;

//定义链接属性

@property (nonatomic,strong)NSURLConnection *connection;


@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    [self createUI];

    

    //创建临时文件,存储下载了多少数据

    self.tempFilePath = [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"tempFile"];

    

    //获得文件的大小

    NSDictionary *infoDic = [[NSFileManagerdefaultManager] attributesOfItemAtPath:self.tempFilePatherror:nil];

    self.tempFileSize = [infoDic[NSFileSize]integerValue];

    

    //为当前数据大小赋值

    self.currentSize =self.tempFileSize;

    

    

    //取一下本地得总长度

    NSNumber *fullSizeNumber = [[NSUserDefaultsstandardUserDefaults] objectForKey:@"currentSize"];

    self.fullFileSize = [fullSizeNumberunsignedLongLongValue];

    

    

    //kvo检测当前数据进度

    [selfaddObserver:selfforKeyPath:@"currentSize"options:NSKeyValueObservingOptionNewcontext:nil];

    

}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{

    

    if ([keyPath isEqualToString:@"currentSize"]) {

        NSNumber *newNumber = change[@"new"];


        //获得新值的大小

        unsigned longlong newSize = [newNumber unsignedLongLongValue];

        //计算当前进度比

        float p = 0;

        if (self.fullFileSize != 0) {

            p = newSize *1.0 / self.fullFileSize;

            self.progressView.progress = p;

            self.progressLabel.text = [NSStringstringWithFormat:@"%.2f%%",p*100];

        }

    }

    

    


}



- (void)createUI{

    self.progressLabel = [[UILabelalloc] initWithFrame:CGRectMake(0, 20,self.view.bounds.size.width,20)];

    self.progressLabel.text =@"0%";

    self.progressLabel.backgroundColor = [UIColorlightGrayColor];

    self.progressLabel.textAlignment =NSTextAlignmentCenter;

    [self.viewaddSubview:self.progressLabel];

    

    

    self.progressView = [[UIProgressViewalloc] initWithFrame:CGRectMake(10, 50,self.view.bounds.size.width - 20, 20)];

    [self.viewaddSubview:self.progressView];

    

    

    self.startButton = [UIButtonbuttonWithType:UIButtonTypeSystem];

    self.startButton.frame =CGRectMake(50, 80, 60, 20);

    [self.startButtonsetTitle:@"开始"forState:UIControlStateNormal];

    [self.startButtonsetTitleColor:[UIColorblueColor] forState:UIControlStateNormal];

    self.startButton.tag = 10;

    [self.startButtonaddTarget:selfaction:@selector(buttonClicked:)forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:self.startButton];

    

    

    self.stopButton = [UIButtonbuttonWithType:UIButtonTypeSystem];

    self.stopButton.frame =CGRectMake(200, 80, 60, 20);

    [self.stopButtonsetTitle:@"停止"forState:UIControlStateNormal];

    [self.stopButtonsetTitleColor:[UIColorblueColor] forState:UIControlStateNormal];

    self.stopButton.tag = 11;

    [self.stopButtonaddTarget:selfaction:@selector(buttonClicked:)forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:self.stopButton];

    

}


- (void)buttonClicked:(UIButton *)button{

    if (button.tag == 10) {

        //开始下载之后让按钮禁止被点击

        self.startButton.enabled =NO;

        

        //开始下载

        NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:[NSURLURLWithString:@"http://dldir1.qq.com/qqfile/QQforMac/QQ_V4.0.2.dmg"]];

        

        //中断下载之后重新开始下载需告知服务器从那一段开始返回数据

        //判断临时文件是否存在存在的话将文件大小与请求头中告知服务器这段数据无需在下载

        NSFileManager *fm = [NSFileManagerdefaultManager];

        if ([fmfileExistsAtPath:self.tempFilePath]) {

            

            NSString *bytesValue = [NSStringstringWithFormat:@"bytes=%lld-",self.tempFileSize];

            //设置请求头

            [request setValue:bytesValue forHTTPHeaderField:@"RANGE"];

        }

        

        //创建连接发起请求

        self.connection = [NSURLConnectionconnectionWithRequest:request delegate:self];

    }else{

        //停止下载

        //停止请求

        [self.connectioncancel];

        if (self.startButton.enabled ==NO) {

            self.startButton.enabled =YES;

        }

        

    }

}


#pragma mark -协议方法

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

    //获得响应头信息,使用nshttpurlresponse强转

    NSDictionary *responseHeaders = [(NSHTTPURLResponse *)responseallHeaderFields];

    

    //获得文件的数据大小

    unsigned longlong contentLength = [responseHeaders[@"Content-Length"]integerValue];

    //获得临时文件判断临时文件是否存在,不存在就创建

    NSFileManager *manager = [NSFileManagerdefaultManager];

    if (![managerfileExistsAtPath:self.tempFilePath]) {

        [manager createFileAtPath:self.tempFilePathcontents:nilattributes:nil];

        //给记录总长度数据的参数赋值

        self.fullFileSize = contentLength;

    }else{

        

        self.fullFileSize =self.tempFileSize + contentLength;

        self.currentSize =self.tempFileSize;

        

    }

    

    //将总数据长度存储于本地

    NSUserDefaults *userDefaults = [NSUserDefaultsstandardUserDefaults];

    

    [userDefaults setObject:@(self.fullFileSize)forKey:@"fullSize"];

    

    [userDefaults synchronize];

    

    //创建一个更新的fileHandle来时刻更新文件的大小

    

    self.fileHand = [NSFileHandlefileHandleForUpdatingAtPath:self.tempFilePath];

    [self.fileHandseekToEndOfFile];

    

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{

    

    self.currentSize += data.length;

    [self.fileHandwriteData:data];

    

    //找到文件所有属性

    NSDictionary *infoDic = [[NSFileManagerdefaultManager] attributesOfItemAtPath:self.tempFilePatherror:nil];

    //获得文件大小

    self.tempFileSize = [infoDic[NSFileSize]integerValue];

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{

    

    

    //下载完成

    //关闭文件

    [self.fileHandcloseFile];

    //开启开始按钮的使用状态

    self.startButton.enabled =YES;

    

    

    //移动到桌面

    NSFileManager *fm = [NSFileManagerdefaultManager];

    NSString *toPath =@"/Users/fudong/Desktop/QQ.dmg";

    //移动

    [fm moveItemAtPath:self.tempFilePathtoPath:toPath error:nil];

    

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{

    //请求失败

    

    [self.fileHandcloseFile];

    self.startButton.enabled =YES;

    

}


- (void)dealloc

{

    [selfremoveObserver:selfforKeyPath:@"currentSize"];

}

- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}




@end


0 0
原创粉丝点击