iOS实现断点续传

NSURLConnection 实现断点续传

controller

//写文件的文件句柄
@property (nonatomic,strong) NSFileHandle *writeHandle;

//当前下载总的字节数
@property (nonatomic) long long currentDownloadByte;

//总文件大小
@property (nonatomic) CGFloat fileSize;

@end

@implementation ViewController
{
NSURLConnection *conn;
}

  • (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSLog(@”%@”,[self getFilePath]);

    //本地文件大小
    NSDictionary *fileInfo = [[NSFileManager defaultManager] attributesOfItemAtPath:[self getFilePath] error:nil];

    self.currentDownloadByte = fileInfo.fileSize;
    self.fileSize = [[[NSUserDefaults standardUserDefaults] objectForKey:@”fileSize”] floatValue];

    if(self.fileSize != 0)
    {
    self.proView.progress = self.currentDownloadByte / self.fileSize;
    self.proLabel.text = [NSString stringWithFormat:@”%.2f%%”,self.proView.progress * 100];
    }
    }

  • (IBAction)pause:(id)sender {
    //暂停下载
    [conn cancel];

    //文件关闭
    [self.writeHandle closeFile];
    }

//文件操作 NSFileHandle —-> 沙盒
-(NSString *)getFilePath
{
return [NSString stringWithFormat:@”%@/Documents/qq.dmg”,NSHomeDirectory()];
}

  • (IBAction)start:(id)sender {
    NSURL *url = [NSURL URLWithString:KCYQQURL];

    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];

    //Range
    //告诉服务器 下载数据范围
    [req setValue:[NSString stringWithFormat:@”bytes=%lld-“,self.currentDownloadByte] forHTTPHeaderField:@”Range”];

    conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
    }

-(void)connection:(NSURLConnection )connection didReceiveResponse:(NSURLResponse )response
{
//得到文件大小
self.fileSize = response.expectedContentLength + self.currentDownloadByte;

[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithFloat:self.fileSize] forKey:@"fileSize"];
[[NSUserDefaults standardUserDefaults] synchronize];

//创建文件
if(![[NSFileManager defaultManager] fileExistsAtPath:[self getFilePath]])
{
    [[NSFileManager defaultManager] createFileAtPath:[self getFilePath] contents:nil attributes:nil];
}

//打开文件  -->  文件指针 默认指向文件头部
self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:[self getFilePath]];

//把文件指针指向文件的尾部
[self.writeHandle seekToEndOfFile];

}

-(void)connection:(NSURLConnection )connection didReceiveData:(NSData )data
{
//把数据写入到文件
[self.writeHandle writeData:data];

self.currentDownloadByte += data.length;
self.proView.progress = self.currentDownloadByte / self.fileSize;
self.proLabel.text = [NSString stringWithFormat:@"%.2f%%",self.proView.progress * 100];

}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//关闭文件
[self.writeHandle closeFile];
}

NSURLSeesion 实现断点续传

@property (nonatomic,strong) NSURLSession *session;

@property (nonatomic,strong) NSURLSessionDownloadTask *downloadTask;

@end

@implementation ViewController

  • (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }

-(void)URLSession:(NSURLSession )session downloadTask:(NSURLSessionDownloadTask )downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
self.proView.progress = totalBytesWritten / (CGFloat)totalBytesExpectedToWrite;
self.proLabel.text = [NSString stringWithFormat:@”%.2f%%”,self.proView.progress * 100];
}

//下载完成的方法 —> 处理下载完成的文件
//location 当前下载数据的缓存文件路径
-(void)URLSession:(NSURLSession )session downloadTask:(NSURLSessionDownloadTask )downloadTask didFinishDownloadingToURL:(NSURL *)location
{
//把文件复制到自己的文件夹里

NSString *qqPath = [NSString stringWithFormat:@"%@/Documents/qq.dmg",NSHomeDirectory()];

if(![[NSFileManager defaultManager] fileExistsAtPath:qqPath])
{
    [[NSFileManager defaultManager] copyItemAtURL:location toURL:[NSURL fileURLWithPath:qqPath] error:nil];
}

}

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

  • (IBAction)pause:(id)sender {

    //暂停下载
    //resumeData 暂停之前 所有下载的数据
    [self.downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
    [[NSUserDefaults standardUserDefaults] setObject:resumeData forKey:@”resumeData”];
    [[NSUserDefaults standardUserDefaults] synchronize];
    }];
    }

  • (IBAction)start:(id)sender {
    NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:@”http://dldir1.qq.com/qqfile/QQforMac/QQ_V4.0.1.dmg“]];

    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@”resumeData”];

    if(data.length == 0)
    {
    self.downloadTask = [self.session downloadTaskWithRequest:req];
    }
    else
    {
    self.downloadTask = [self.session downloadTaskWithResumeData:data];
    }

    [self.downloadTask resume];
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值