iOS开发中文件的上传和下载功能的基本实现

2020-01-14 17:11:52于海丽

{
    
}

/**
 *  2. 当接受到服务器的数据就会调用(可能会被调用多次, 每次调用只会传递部分数据)
 */
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // 移动到文件的尾部
    [self.writeHandle seekToFileOffset:self.begin + self.currentLength];
    // 从当前移动的位置(文件尾部)开始写入数据
    [self.writeHandle writeData:data];
    
    // 累加长度
    self.currentLength += data.length;
    
    // 打印下载进度
    double progress = (double)self.currentLength / (self.end - self.begin);
    if (self.progressHandler) {
        self.progressHandler(progress);
    }
}

/**
 *  3. 当服务器的数据接受完毕后就会调用
 */
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // 清空属性值
    self.currentLength = 0;
    
    // 关闭连接(不再输入数据到文件中)
    [self.writeHandle closeFile];
    self.writeHandle = nil;
}

/**
 *  请求错误(失败)的时候调用(请求超时断网没有网, 一般指客户端错误)
 */
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    
}

@end


设计多线程下载器(利用HMFileMultiDownloader能开启多个线程同时下载一个文件)

 

一个多线程下载器只下载一个文件

YYFileMultiDownloader.h文件

复制代码
#import "YYFileDownloader.h"

 

@interface YYFileMultiDownloader : YYFileDownloader
 
@end


YYFileMultiDownloader.m文件
复制代码
#import "YYFileMultiDownloader.h"
#import "YYFileSingleDownloader.h"

 

#define YYMaxDownloadCount 4