iOS 简单的分段下载文件

时间:2024-03-24 13:07:44

首先自己写个请求数据的类

首先.h文件

#import <Foundation/Foundation.h>

@interface Downloaders : NSObject<NSURLConnectionDataDelegate>

@property (nonatomic, assign) long long beginpt;//下载的起始点

@property (nonatomic, assign) long long endpt;//下载的终点

@property(nonatomic,assign)long long currentLength;//下载的长度

@property(nonatomic,retain)NSString *url;

-(void)starts;

@end

.m文件

#import "Downloaders.h"

#import <Foundation/Foundation.h>

@implementation Downloaders

{

}

-(id)init

{

self = [super init];

if(self)

{

}

return self;

}

-(void)starts

{

[self startDown];

}

-(void)startDown

{

NSURL *urls =[NSURL URLWithString:self.url];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:urls];

NSString *value = [NSString stringWithFormat:@"bytes=%lld-%lld", self.beginpt + self.currentLength, self.endpt];

[request setValue:value forHTTPHeaderField:@"Range"];

[NSURLConnection connectionWithRequest:request delegate:self];

}

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

{

NSString *path = [NSHomeDirectory()stringByAppendingString:@"/Documents"];

NSString *fullpath = [path stringByAppendingPathComponent:@"tests.mp4"];

NSFileManager *fiels= [NSFileManager defaultManager];

if(![fiels fileExistsAtPath:fullpath])

{

[fiels createFileAtPath:fullpath contents:nil attributes:nil];

}

else

{

//  NSLog(@"fiel exsits......");

}

NSFileHandle *fielhandel = [NSFileHandle fileHandleForUpdatingAtPath:fullpath];

[ fielhandel seekToFileOffset:self.beginpt + self.currentLength ];

[fielhandel writeData:data];

self.currentLength += data.length;

}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection

{

self.currentLength = 0;

}

然后在需要的地方调用

#import "ViewController.h"

#import "Downloaders.h"

@interface ViewController ()

{

long long totallength;

}

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

[self getfielsize];

long long sizes= 0;

sizes  = totallength/4+1;

for(int i=0;i<4;i++)

{

Downloaders *objc = [[Downloaders alloc]init];

objc.url = @"http://172.16.1.92:97/meadia/test.mp4";

objc.beginpt = i*sizes;

objc.endpt = objc.beginpt+sizes-1;

[objc starts];

}

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

}

-(void)getfielsize

{

NSString *str = @"http://172.16.1.92:97/meadia/test.mp4";

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

request.HTTPMethod=@"HEAD";

NSURLResponse *response = nil;

[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

totallength = response.expectedContentLength;

}

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

@end