歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> iOS 實現斷點續傳 一 nsurlconnection

iOS 實現斷點續傳 一 nsurlconnection

日期:2017/3/1 10:29:06   编辑:Linux編程
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. -(void)writeToFile:(NSData *)data fileName:(NSString *) fileName
  8. {
  9. NSString *filePath=[NSString stringWithFormat:@"%@",fileName];
  10. if([[NSFileManager defaultManager] fileExistsAtPath:filePath] == NO){
  11. NSLog(@"file not exist,create it...");
  12. [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
  13. }else {
  14. NSLog(@"file exist!!!");
  15. }
  16. FILE *file = fopen([fileName UTF8String], [@"ab+" UTF8String]);
  17. if(file != NULL){
  18. fseek(file, 0, SEEK_END);
  19. }
  20. int readSize = [data length];
  21. fwrite((const void *)[data bytes], readSize, 1, file);
  22. fclose(file);
  23. }
Copyright © Linux教程網 All Rights Reserved