断点续传

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来定义头部域

    1. NSURL *url1=[NSURL URLWithString:@"下载地址";  
    2. NSMutableURLRequest* request1=[NSMutableURLRequest requestWithURL:url1];  
    3. [request1 setValue:@"bytes=20000-" forHTTPHeaderField:@"Range"];   
    4. [request1 setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];  
    5. NSData *returnData1 = [NSURLConnection sendSynchronousRequest:request1 returningResponse:nil error:nil];   
    6. [self writeToFile:returnData1 fileName:@"SOMEPATH"];  
    7.   
    8.   
    9.   
    10.   
    11. -(void)writeToFile:(NSData *)data fileName:(NSString *) fileName  
    12. {  
    13.     NSString *filePath=[NSString stringWithFormat:@"%@",fileName];  
    14.     if([[NSFileManager defaultManager] fileExistsAtPath:filePath] == NO){  
    15.         NSLog(@"file not exist,create it...");  
    16.         [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];  
    17.     }else {  
    18.     NSLog(@"file exist!!!");  
    19.     }  
    20.   
    21.     FILE *file = fopen([fileName UTF8String], [@"ab+" UTF8String]);  
    22.   
    23.     if(file != NULL){  
    24.         fseek(file, 0, SEEK_END);  
    25.     }  
    26.     int readSize = [data length];  
    27.     fwrite((const void *)[data bytes], readSize, 1, file);  
    28.     fclose(file);  
    29. }  
原文地址:https://www.cnblogs.com/chenhaosuibi/p/3551795.html