zoukankan      html  css  js  c++  java
  • 网络编程练习 -- 大文件下载

    LWTViewController.m

    //
    //  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

    //
    //  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

    //
    //  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
  • 相关阅读:
    Flutter实战视频-移动电商-11.首页_屏幕适配方案讲解
    Flutter实战视频-移动电商-10.首页_FlutterSwiper轮播效果制作
    Flutter实战视频-移动电商-09.首页_项目结构建立和获取数据
    Flutter实战视频-移动电商-08.Dio基础_伪造请求头获取数据
    【RQNOJ】460 诺诺的队列
    NYOJ 483 Nightmare 【广搜】+【无标记】
    冒泡,简单选择,直接插入排序(Java版)
    基于MFC与第三方类CWebPage的百度地图API开发范例
    USACO 1.2 Palindromic Squares (进制转换,回文)
    与《新走遍美国》的邂逅
  • 原文地址:https://www.cnblogs.com/wentianblog/p/3820767.html
Copyright © 2011-2022 走看看