ios开发网络-大文件的多线程断点下载

说明:本文介绍多线程断点续传。项目中使用了苹果自带的类,实现了同时开启多条线程下载一个较大的文件。 因为实现过程较为复杂,

实现思路:下载 开始,创建一个与要下载文件大小相同的文件(如果要下载100M,那么就在沙盒创建一个100M的文件,然后计算每一段的下载量,开启多条线程下载各段的数据,分别写入对应的文件部分)。

项目用到如下类:


完成的实现代码如下:

主控制器的代码:


#import "YYViewController.h"
#import "YYFileMultiDownloader.h"

@interface YYViewController ()
@property (nonatomic, strong) YYFileMultiDownloader *fileMultiDownloader;
@end

@implementation YYViewController
-  (YYFileMultiDownloader *)fileMultiDownloader
{
    if (!_fileMultiDownloader) {
        _fileMultiDownloader = [[YYFileMultiDownloader alloc] init];
        // 需要下载的文件远程URL
        _fileMultiDownloader.url = @"http://192.168.1.200:8080/MJServer/resources/jre.zip";
        // 文件保存到什么地方
        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filepath = [caches stringByAppendingPathComponent:@"jre.zip"];
        _fileMultiDownloader.destPath = filepath;
    }
    return _fileMultiDownloader;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
}

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

@end

自定义一个基类

YYFileDownloader.h文件

#import <Foundation/Foundation.h>

@interface YYFileDownloader : NSObject
{
    BOOL _downloading;
}
/**
 * 所需要下载文件的远程URL(连接服务器的路径)
 */
@property (nonatomic, copy) NSString *url;
/**
 * 文件的存储路径(文件下载到什么地方)
 */
@property (nonatomic, copy) NSString *destPath;

/**
 * 是否正在下载(有没有在下载, 只有下载器内部才知道)
 */
@property (nonatomic, readonly, getter = isDownloading) BOOL downloading;

/**
 * 用来监听下载进度
 */
@property (nonatomic, copy) void (^progressHandler)(double progress);

/**
 * 开始(恢复)下载
 */
- (void)start;

/**
 * 暂停下载
 */
- (void)pause;
@end


猜你喜欢

转载自blog.csdn.net/chaoge321/article/details/50846318
今日推荐