利用NSFileHandle进行文件的下载

#import "ViewController.h"

@interface ViewController () <NSURLConnectionDataDelegate>

@property (strong, nonatomic) NSFileHandle *downloadFileHandle;

@end

@implementation ViewController




- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

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

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    
    [self download2];
}

//运用NSFileHandle下载
- (void)download2
{
    //http请求
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.23.100/ios/01.mp4"]];
    
    //文件保存路径
    NSString *file_save_path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    file_save_path = [file_save_path stringByAppendingPathComponent:@"my.mp4"];
    
    //利用NSFileManager创建一个空文件
    NSFileManager *file_manager = [NSFileManager defaultManager];
    [file_manager createFileAtPath:file_save_path contents:nil attributes:nil];

    //创建文件资源
    self.downloadFileHandle = [NSFileHandle fileHandleForWritingAtPath:file_save_path];
    
    //执行请求
    [NSURLConnection connectionWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"下载错误");
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"开始下载");
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"这次下载了%lu",(unsigned long)data.length);
    [self.downloadFileHandle seekToEndOfFile];
    
    [self.downloadFileHandle writeData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"下载成功!");
    [self.downloadFileHandle closeFile];
    self.downloadFileHandle = nil;
}


@end


你可能感兴趣的:(文件下载,NSFileHandle)