ios实现断点下载
#import "ZYDownViewController.h"
@interface ZYDownViewController ()
@end
@implementation ZYDownViewController
{
// NSMutableData * buffer;
long long _totalLength; //文件总大小
long long _currentLength; //当前下载大小 默认为0
NSFileHandle * fileHandle;
NSURLConnection * conn;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
NSString * pp=[self getPath];
fileHandle =[NSFileHandle fileHandleForWritingAtPath:pp];
_progress.progressViewStyle=1;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
//buffer=[[NSMutableData alloc] init];
_totalLength=[response expectedContentLength] + _currentLength;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
//[buffer appendData:data];
if (fileHandle) {
//定位到要写入文件的地方
[fileHandle seekToFileOffset:[fileHandle seekToEndOfFile]];
[fileHandle writeData:data];
}
_currentLength+=data.length;
float f=(float)_currentLength/(float)_totalLength;
_progress.progress=f;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
UIAlertView * alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"下载成功" delegate:self cancelButtonTitle:@"返回" otherButtonTitles:nil, nil];
[alert show];
}
- (IBAction)DownBtnClick:(id)sender {
//断点下载
NSString * path=[self getPath]; //获取路径
long long filesize=0;
NSFileManager * fileMg=[NSFileManager defaultManager];
//获取文件信息字典
NSDictionary *dic=[fileMg attributesOfItemAtPath:path error:nil];
// 获取文件大小
NSNumber * contentLength=[dic objectForKey:NSFileSize];
//获取已经下载多少
filesize=[contentLength longLongValue];
_currentLength=filesize;
//获取下载文件的大小
NSURL * url=[NSURL URLWithString:@"http://localhost:8080/Servelet/3333.dmg"]; //测试服务代码
NSMutableURLRequest * request=[NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
//设置请求过后的字节 因为我们要求都是在建立在已经获取文件的大小的基础上的进行的
[request addValue:[NSString stringWithFormat:@"bytes=%qu-",_currentLength] forHTTPHeaderField:@"Range"];
conn=[NSURLConnection connectionWithRequest:request delegate:self];
}
-(NSString *) getPath{
NSString * filePath=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/test.dmg"];
NSFileManager * fileMg=[NSFileManager defaultManager];
if (![fileMg fileExistsAtPath:filePath]) {
[fileMg createFileAtPath:filePath contents:nil attributes:nil];
}
return filePath;
}
- (IBAction)CancelBtnClick:(id)sender {
[conn cancel];
}
@end
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。