ios断点续传实现

本文详细介绍了如何使用Objective-C实现iOS设备上的文件下载,并通过UIProgressView实时显示下载进度。包括文件目录创建、文件下载请求设置、响应处理、数据接收与进度更新等关键步骤。

#import <UIKit/UIKit.h>

@interface DownLoadViewController : UIViewController <NSURLConnectionDataDelegate>

{

    //_receivedSize 已下载数据的大小

    //_totalSize 下载数据的总大小

    long long _receivedSize, _totalSize;

}

@property(nonatomic,retain)NSURLConnection *coon;

@property(nonatomic,retain)NSFileHandle *fileHandle;

//在xib中给下面这四个控件连一下线

@property (retainnonatomicIBOutlet UIProgressView *downProgressView;

@property (retain, nonatomic) IBOutlet UIImageView *downLoadImageView;

- (IBAction)downLoadAction:(id)sender;

- (IBAction)stopDownLoad:(id)sender;

@end

ViewController.m 中

#pragma mark  下载

- (IBAction)downLoadAction:(id)sender

{

    NSFileManager *manager = [NSFileManager defaultManager];

    //dir ——directory(文件夹)

    NSString *dirPath =[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/today/movie/"];

    //首先判断文件夹是否存在

    if (![manager fileExistsAtPath:dirPath]) {

        //文件不存在,创建之

        //withIntermediateDirectories:是否自动创建中间文件

        [manager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil];

    }

    

    NSString *filePath = [dirPath stringByAppendingPathComponent:@"1.mp4"];

    if (![manager fileExistsAtPath:filePath]) {

        //参数一:创建文件路径

        //参数二:文件中要写入的数据

        //参数三:文件的属性(权限,创建日期etc..

        BOOL  ret = [manager createFileAtPath:filePath contents:nil attributes:nil];

        if (ret) {

            NSLog(@"文件创建成功");

        }

    }

    

    //得到文件的属性

    NSDictionary *fileInfo = [manager attributesOfItemAtPath:filePath error:nil];

    //从文件属性字典中的文件大小

    _receivedSize = [[fileInfo objectForKey:NSFileSize] longLongValue];

    

    //handle——句柄

    //NSFileHandle——指向文件,操作这个文件

    self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];

    

    //---------------------------------------------------

    

    //图片地址:@"http://localhost:8080/Web2/1.JPG"

    NSString *urlString = [@"http://localhost:8080/Web1/1.mp4" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSLog(@"%@", urlString);

    

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];

    //Host:www.baidu.com

    //content-type:rtf

    //connection:close

    //Range: bytes= 起始位置-结束位置

    //Range:bytes=0-29  //下载前30个字节

    //Range:bytes=30-89 //下载中间60字节

    //Range:bytes=90-     //下载91字节开始一直到最后

    //Range:bytes=10-    //下载从11字节开始一直到最后

    [request setValue:[NSString stringWithFormat:@"bytes=%lld-", _receivedSize] forHTTPHeaderField:@"range"];

    

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

    

}

#pragma mark 停止下载

- (IBAction)stopDownLoad:(id)sender

{

    //取消下载链接

    [self.coon cancel];

    //关闭文件操作句柄,把数据写到指定文件

    [self.fileHandle closeFile];

}

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

{

//    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;

//    NSLog(@"__%@", httpResponse.allHeaderFields);

    //保存文件总大小

    //断点下载时,总下载长度= 已下载长度 + 剩余数据长度

    _totalSize = _receivedSize + response.expectedContentLength;

    

    NSLog(@"__%lld",response.expectedContentLength);

    

}

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

{

//    data.length

    _receivedSize += data.length;

//    NSLog(@"已下载大小 %lld,  剩余数据 %lld", _receivedSize, _totalSize - _receivedSize);

    

    float downProgress = (float)_receivedSize / _totalSize;

    NSLog(@"下载进度 == %f", downProgress);

    

    //在进度条上显示当前下载进度百分比

    self.downProgressView.progress = downProgress;

    //seekToEndOfFile——指向文件的末尾

    [self.fileHandle seekToEndOfFile];

    

    //在文件的末尾添加新的数据

    [self.fileHandle writeData:data];

}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    NSLog(@"文件下载完毕");

    [self.fileHandle closeFile];

}

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

{

    NSLog(@"__%@", error);

}

- (void)dealloc {

    [_downProgressView release];

    [super dealloc];

}

@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值