码迷,mamicode.com
首页 > 其他好文 > 详细

网络编程练习 -- 大文件下载

时间:2014-07-03 23:08:37      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   strong   

LWTViewController.m

bubuko.com,布布扣
//
//  LWTViewController.m
//  网络编程练习 -- 大文件下载
//
//  Created by apple on 14-6-28.
//  Copyright (c) 2014年 lwt. All rights reserved.
//

#import "LWTViewController.h"
#import "LWTFileDownloadTool.h"

@interface LWTViewController () <NSURLConnectionDataDelegate>

@property (weak, nonatomic) IBOutlet UIProgressView *progressView;

@property (nonatomic, strong) LWTFileDownloadTool *fileDownloadTool;

- (IBAction)start : (UIButton *)button;

@end

@implementation LWTViewController

- (LWTFileDownloadTool *)fileDownloadTool
{
    if (nil == _fileDownloadTool) {
//        _fileDownloadTool = [[LWTFileDownloadTool alloc] init];
        _fileDownloadTool = [LWTFileDownloadTool fileDownloadTool];
        
        _fileDownloadTool.url = @"http://192.168.1.24:8080/MJServer/resources/video.zip";
        
        NSArray *array = [_fileDownloadTool.url componentsSeparatedByString:@"/"];
        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        _fileDownloadTool.desturl = [caches stringByAppendingPathComponent:[array lastObject]];
        
        __weak typeof(self) weakVC = self;
        
        _fileDownloadTool.progressHandler = ^(double progress){
            weakVC.progressView.progress = progress;
        };
        
        _fileDownloadTool.completionHandler = ^(){
            NSLog(@"下载完成");
        };
        
        _fileDownloadTool.failureHandler = ^(NSError *error){
            NSLog(@"%@", error);
        };
        
        
    }
    return _fileDownloadTool;
}

- (IBAction)start : (UIButton *)button{
    
    if (self.fileDownloadTool.isDownloading) {
        [button setTitle:@"恢复" forState:UIControlStateNormal];
        [self.fileDownloadTool pause];
    }else{
        [button setTitle:@"暂停" forState:UIControlStateNormal];
        [self.fileDownloadTool begin];
    }
}

@end
View Code

LWTFileDownloadTool.h

bubuko.com,布布扣
//
//  LWTFileDownloadTool.h
//  网络编程练习 -- 大文件下载
//
//  Created by apple on 14-6-28.
//  Copyright (c) 2014年 lwt. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface LWTFileDownloadTool : NSObject
/**
 * 所需要下载文件的远程URL(连接服务器的路径)
 */
@property (nonatomic, copy) NSString *url;
/**
 * 文件的存储路径(文件下载到什么地方)
 */
@property (nonatomic, copy) NSString *desturl;
/**
 * 是否正在下载(有没有在下载, 只有下载器内部才知道)
 */
@property (nonatomic, readonly, getter = isDownloading) BOOL downloading;
/**
 * 用来监听下载进度
 */
@property (nonatomic, copy) void(^progressHandler) (double progress);
/**
 * 用来监听下载完毕
 */
@property (nonatomic, copy) void(^completionHandler)();
/**
 * 用来监听下载失败
 */
@property (nonatomic, copy) void(^failureHandler)(NSError *error);
/**
 * 开始(恢复)下载
 */
- (void)begin;
/**
 * 暂停下载
 */
- (void)pause;


+ (instancetype)fileDownloadTool;

@end
View Code

LWTFileDownloadTool.m

bubuko.com,布布扣
//
//  LWTFileDownloadTool.m
//  网络编程练习 -- 大文件下载
//
//  Created by apple on 14-6-28.
//  Copyright (c) 2014年 lwt. All rights reserved.
//

#import "LWTFileDownloadTool.h"

@interface LWTFileDownloadTool () <NSURLConnectionDataDelegate>

@property (nonatomic, strong) NSURLConnection *conn;

@property (nonatomic, strong) NSFileHandle *writeHandle;

@property (nonatomic, assign) long long totalLength;

@property (nonatomic, assign) long long currentLength;


@end

@implementation LWTFileDownloadTool

+ (instancetype)fileDownloadTool
{
    return [[self alloc] init];
}

- (void)begin
{
    _downloading = YES;
    
    NSString *urlStr = [self.url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:urlStr];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    NSString *value = [NSString stringWithFormat:@"bytes=%lld-", self.currentLength];
    [request setValue:value forHTTPHeaderField:@"Range"];
    
    self.conn = [NSURLConnection connectionWithRequest:request delegate:self];
}

- (void)pause
{
    _downloading = NO;
    [self.conn cancel];
    self.conn = nil;
}

#pragma mark - NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    
    if (self.writeHandle) return;
    
    NSFileManager *manager = [NSFileManager defaultManager];
    [manager createFileAtPath:self.desturl contents:nil attributes:nil];
    
    self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:self.desturl];
    
    self.totalLength = response.expectedContentLength;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    self.currentLength += data.length;
    
    double progress = (double)self.currentLength / self.totalLength;
    if (self.progressHandler) {
        self.progressHandler(progress);
    }
    
    [self.writeHandle seekToEndOfFile];
    [self.writeHandle writeData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    if (self.failureHandler) {
        self.failureHandler(error);
    }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if (self.completionHandler) {
        self.completionHandler();
    }
    
    self.currentLength = 0;
    self.totalLength = 0;
    
    [self.writeHandle closeFile];
    self.writeHandle = nil;
}
@end
View Code

 

网络编程练习 -- 大文件下载,布布扣,bubuko.com

网络编程练习 -- 大文件下载

标签:des   style   blog   http   color   strong   

原文地址:http://www.cnblogs.com/wentianblog/p/3820767.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!