First, write a class of request data
First. h file
#import <Foundation/Foundation.h>
@interface downloaders:nsobject<nsurlconnectiondatadelegate>
@property (nonatomic, assign) long long beginpt;//download starting point
@property (nonatomic, assign) long long endpt;//The end of the download
@property (nonatomic,assign) long long currentlength;//download length
@property (Nonatomic,retain) NSString *url;
-(void) starts;
@end
. m file
#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;
}
and call it where it's needed.
#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];
}
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];
[Email protected] "HEAD";
Nsurlresponse *response = nil;
[Nsurlconnection sendsynchronousrequest:request returningresponse:&response Error:nil];
Totallength = Response.expectedcontentlength;
}
-(void) didreceivememorywarning {
[Super didreceivememorywarning];
Dispose of any resources the can be recreated.
}
@end
IOS Simple segmented download file