標籤:
#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
ios實現斷點下載