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

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

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

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

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

时间: 2024-08-28 12:15:58

网络编程练习 -- 大文件下载的相关文章

网络编程---(数据请求+slider)将网络上的大文件下载到本地,并打印其进度

网络编程---将网络上的大文件下载到本地,并打印其进度. 点击"开始传输"按钮,将网络上的大文件先下载下来,下载完成后,保存到本地. UI效果图如下:            具体代码如下: //  ViewController.m //  0611---数据请求+滚动条 #import "ViewController.h" unsigned long tempLength; @interface ViewController () <NSURLConnecti

【iOS开发-网络】关于大文件下载

大文件下载要使用NSURLConnection的代理方法 首先创建好url发出请求 //创建url NSURL *url = [NSURL URLWithString:@"http://localhost:8080/TFServer/resources/videos/minion_01.mp4"]; //创建请求 NSURLRequest *request = [NSURLRequest requestWithURL:url]; //发出一个异步请求 [NSURLConnection

iOS多线程与网络开发之大文件下载 (边下边写/暂停恢复下载/压缩解压zip/多线程下载)

郝萌主倾心贡献,尊重作者的劳动成果,请勿转载. 如果文章对您有所帮助,欢迎给作者捐赠,支持郝萌主,捐赠数额随意,重在心意^_^ 我要捐赠: 点击捐赠 Cocos2d-X源码下载:点我传送 游戏官方下载:http://dwz.cn/RwTjl 游戏视频预览:http://dwz.cn/RzHHd 游戏开发博客:http://dwz.cn/RzJzI 游戏源码传送:http://dwz.cn/Nret1 A.需求 边下边写入硬盘 显示下载进度 暂停/恢复 下载 解压文件 多线程下载 B.基本知识 1

Linux Linux程序练习十(网络编程大文件发送)

//网络编程客户端--大文件传输 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/ine

Linux Linux程序练习十一(网络编程大文件发送UDP版)

//网络编程发送端--大文件传输(UDP) #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arp

iOS开发之网络编程--使用NSURLConnection实现大文件下载

主要思路(实现下载数据分段写入缓存中) 1.使用NSURLConnectionDataDelegate以及代理方法.2.在成功获取响应的代理方法中,获得沙盒全路径,并在该路径下创建空文件和文件句柄.3.在获取data的代理方法中,先设置句柄在沙盒全路径文件末尾,然后通过句柄写入data数据.4.在文件下载完的代理方法中,关闭句柄同时设置句柄引用为nil释放句柄和指针. 使用句柄的思路图(红色的箭头表示句柄,灰色的箭头表示移动的路径): 代码关键词: 类:NSFileHandle的方法 1.fil

iOS开发之网络编程--2、NSURLSessionDownloadTask文件下载

本文内容大纲: 1.回顾NSURLSessionTask 2.NSURLSessionDownloadTask大文件之block下载 3.NSURLSessionDownloadTask大文件之代理方法下载 4.NSURLSessionDownloadTask大文件之代理方法实现断点续传下载 前言:如果读者是第一次阅读或者是学习关于本篇要介绍的NSURLSession的知识,最好先阅读本人前篇<iOS开发之网络编程--1.NSURLSession的基本使用>然后再学习本篇比较好. 1.回顾NS

iOS开发之网络编程--使用NSURLConnection实现大文件断点续传下载+使用输出流代替文件句柄

前言:本篇讲解,在前篇iOS开发之网络编程--使用NSURLConnection实现大文件断点续传下载的基础上,使用输出流代替文件句柄实现大文件断点续传.    在实际开发中,输入输出流用的比较少,但是用起来也是很方便的.iOS开发用到的输入输出流和在Java中的输入输出流是几乎一样的,本质也是一个意思:将网络返回的数据当做流来处理.    输入输出的理解:输入到哪里?输出到哪里?这个问题不难理解,输入输出是要站着服务器角度来思考的,下面用图来解释:    代码关键词: 1.在接收到响应头的代理

ios开发网络学习三:NSURLConnection小文件大文件下载

一:小文件下载 #import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelegate> /** 注释 */ @property (nonatomic, strong) NSMutableData *fileData; @property (nonatomic, assign) NSInteger totalSize; @property (weak, nonatomic) IB