ios 实现断点续传 一 nsurlconnection

来源:互联网 发布:mac 动画制作软件 编辑:程序博客网 时间:2024/05/02 10:38
NSUrlConnection实现断点续传的关键是自定义http request的头部的range域属性。


 Range头域
  Range头域可以请求实体的一个或者多个子范围。例如,
  表示头500个字节:bytes=0-499
  表示第二个500字节:bytes=500-999
  表示最后500个字节:bytes=-500
  表示500字节以后的范围:bytes=500-
  第一个和最后一个字节:bytes=0-0,-1
  同时指定几个范围:bytes=500-600,601-999
  但是服务器可以忽略此请求头,如果无条件GET包含Range请求头,响应会以状态码206(PartialContent)返回而不是以200(OK)。


在ios中使用NSMutableURLRequest来定义头部域
NSURL *url1=[NSURL URLWithString:@"下载地址";NSMutableURLRequest* request1=[NSMutableURLRequest requestWithURL:url1];[request1 setValue:@"bytes=20000-" forHTTPHeaderField:@"Range"]; [request1 setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];NSData *returnData1 = [NSURLConnection sendSynchronousRequest:request1 returningResponse:nil error:nil]; [self writeToFile:returnData1 fileName:@"SOMEPATH"];-(void)writeToFile:(NSData *)data fileName:(NSString *) fileName{    NSString *filePath=[NSString stringWithFormat:@"%@",fileName];    if([[NSFileManager defaultManager] fileExistsAtPath:filePath] == NO){        NSLog(@"file not exist,create it...");        [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];    }else {    NSLog(@"file exist!!!");    }    FILE *file = fopen([fileName UTF8String], [@"ab+" UTF8String]);    if(file != NULL){        fseek(file, 0, SEEK_END);    }    int readSize = [data length];    fwrite((const void *)[data bytes], readSize, 1, file);    fclose(file);}


原创粉丝点击