iOS AFN进行断点下载

来源:互联网 发布:od软件 编辑:程序博客网 时间:2024/05/22 15:15
//
//  ViewController.m
//  Download
//
//  Created by Congwang on 14/6/29.
//  Copyright (c) 2014 Congwang. All rights reserved.
//

#import "ViewController.h"
#import
 "AFNetworking.h"
@interface ViewController ()
@property (retain, nonatomic) IBOutlet UIProgressView *sliderView;
@property (retain, nonatomic) IBOutlet UILabel *progress;
@property (nonatomic, retain) AFHTTPRequestOperation  * operation;
@end

@implementation ViewController

- (
void)viewDidLoad {
    [
super viewDidLoad];
   
 NSString * txtTempPath =[ NSTemporaryDirectory()stringByAppendingPathComponent:@"mvTemp/mv.txt"];
 
NSFileManager  fileManager =[NSFileManager defaultManager];
   
 if ([fileManager fileExistsAtPath:txtTempPath])
    {
       
 _sliderView.progress  [[NSStringstringWithContentsOfFile:txtTempPathencoding:NSUTF8StringEncoding error:nil] floatValue];
    }
   
   
 else _sliderView.progress = 0;
   
 _progress.text = [NSStringstringWithFormat:@"%.2f%%",_sliderView.progress *100];
   
 // Do any additional setup after loading the view from its nib.
   
   
 NSLog(@"%@", NSHomeDirectory());
}

- (
void)didReceiveMemoryWarning {
    [
super didReceiveMemoryWarning];
   
 // Dispose of any resources that can be recreated.
}



- (
IBAction)start:(UIButton *)sender
{
  
 if([sender.currentTitle isEqualToString:@"开始下载"])
      {
          [sender
 setTitle:@"暂停下载"forState:UIControlStateNormal];
   
   
 NSURL * url = [NSURLURLWithString:@"http://www.demaxiya.com/app/index.php?m=play&vid=29996&quality=1"];
   
 NSString * CachePath =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask,YES)firstObject];
   
 NSFileManager  fileManager =[NSFileManager defaultManager];
  
 NSLog(@"%@",CachePath);
   
 NSString * folderPath = [CachePath stringByAppendingPathComponent:@"mv"];
   
 NSString * tempPath =[ NSTemporaryDirectory()stringByAppendingPathComponent:@"mvTemp"];
 
 //判断缓存文件夹和视频存放文件夹是否存在,如果不存在,就创建一个文件夹
   
 if (![fileManager fileExistsAtPath:folderPath])
    {
        [fileManager
 createDirectoryAtPath:folderPathwithIntermediateDirectories:YES attributes:nil error:nil];
    }
//
   
 if (![fileManager fileExistsAtPath:tempPath])
    {
        [fileManager
 createDirectoryAtPath:tempPathwithIntermediateDirectories:YES attributes:nil error:nil];
    }

   
 NSString * tempFilePath = [tempPath stringByAppendingPathComponent:@"mv.temp"];//缓存路径
   
 NSString * mvFilePath = [folderPath stringByAppendingPathComponent:@"mv.mp4"];//文件保存路径
   
 NSString * txtFilePath = [tempPath stringByAppendingPathComponent:@"mv.txt"];//保存重启程序下载的进度
 
      
 unsigned long long  downloadedBytes =0;
   
 NSURLRequest * request = [NSURLRequest  requestWithURL:url];
   
   
 if ([fileManager fileExistsAtPath:tempFilePath])//如果存在,说明有缓存文件
    {
        downloadedBytes = [
self fileSizeAtPath:tempFilePath];//计算缓存文件的大小
       
 NSMutableURLRequest *mutableURLRequest = [requestmutableCopy];
       
 NSString *requestRange = [NSStringstringWithFormat:@"bytes=%llu-", downloadedBytes];
       
        [mutableURLRequest
 setValue:requestRangeforHTTPHeaderField:@"Range"];
        request = mutableURLRequest;
       
 NSLog(@"==============断点下载");
    }

   
   
 if (![fileManager  fileExistsAtPath:mvFilePath]) {
       
        [[
NSURLCache sharedURLCache] removeCachedResponseForRequest:request];
      
 self.operation= [[AFHTTPRequestOperation alloc]initWithRequest:request];
        [
_operation setOutputStream:[NSOutputStreamoutputStreamToFileAtPath: tempFilePath append:YES]];
     
        [
_operation  setDownloadProgressBlock:^(NSUIntegerbytesRead, long long totalBytesRead, long longtotalBytesExpectedToRead) {
           
 _sliderView.progress = ((float)totalBytesRead + downloadedBytes) / (totalBytesExpectedToRead + downloadedBytes);
           
 _progress.text = [NSStringstringWithFormat:@"%.2f%%",_sliderView.progress *100];
         
           
 NSString * progress = [NSStringstringWithFormat:@"%.3f",((float)totalBytesRead + downloadedBytes) / (totalBytesExpectedToRead + downloadedBytes)];
            [progress
 writeToFile:txtFilePath atomically:YESencoding:NSUTF8StringEncoding error:nil];
        }];
       
        [
_operation  setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
         {
            
             [fileManager
 moveItemAtPath:tempFilePathtoPath:mvFilePath error:nil];//把下载完成的文件转移到保存的路径
              [fileManager
 removeItemAtPath:txtFilePatherror:nil];//删除保存进度的txt文档
            
            
         }
 failure:^(AFHTTPRequestOperation *operation, NSError*error)
        
         {
            
            
         }];
        [
_operation start];
    }
else
    {
       
    }
      }
     
 else
      {
         
          [sender
 setTitle:@"开始下载"forState:UIControlStateNormal];
          [
self.operation cancel];
          
 self.operation = nil;
         
      }
   
}
//计算缓存文件大小的方法
- (
unsigned long long)fileSizeAtPath:(NSString *)fileAbsolutePath {
   
 signed long long fileSize = 0;
   
 NSFileManager *fileManager = [NSFileManager new];
   
 if ([fileManager fileExistsAtPath:fileAbsolutePath]) {
       
 NSError *error = nil;
       
 NSDictionary *fileDict = [fileManagerattributesOfItemAtPath:fileAbsolutePath error:&error];
       
 if (!error && fileDict) {
            fileSize = [fileDict
 fileSize];
        }
    }
   
 return fileSize;
}

@end
iOS <wbr>AFN进行断点下载
0 0
原创粉丝点击