首页 > 学院 > 开发设计 > 正文

服务器文件下载

2019-11-14 18:18:42
字体:
来源:转载
供稿:网友

文件下载基本步骤:
1.获取下载链接,创建响应发送请求.(使用异步请求,避免因文件过大下载时间长而阻塞主线程).
2.当接到响应时在下载目录中创建文件.创建文件使用NSFileHandle进行文件内部处理.(检验文件是否存在——利用NSFileManager创建文件——NSFileHandle的fileHandleForWritingAtPath方法对文件进行写入).
3.接收数据时,将分段接收的数据写入文件中
4.文件接收完毕后,关闭NSFileHandle.
以上为普通下载步骤,此处不用代码示范,以下以实现断点下载功能为例.

因为沙盒路径在本程序中经常使用,所以先提供一个获取沙盒路径方法

-(NSString *)getFilePath{    NSString *document=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];    NSString *filePath=[document stringByAppendingPathComponent:_fileName];    return filePath;}

下载事件

- (IBAction)download:(UIButton *)sender {    //获取视频地址URL    NSString *string=@"http://221.228.249.8/2/b/k/h/o/bkhoxvtmbviswrdeddgvxcbufzwvwb/he.yinyuetai.com/631B014A6B0FCDF25944EB816345F6A6.flv";    //对地址按"/"分隔存入数组,获取文件名称    NSArray *array=[string componentsSeparatedByString:@"/"];    _fileName=[array lastObject];    //对url进行转码(当地址中存在汉子时无法无法识别,需将其转换成符合要求的格式)    string=[string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];    NSURL *url=[NSURL URLWithString:string];    //可变响应,因为断点下载再次发送请求的位置与之前不同    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];    //判断之前有没有下载数据(沙盒中是否已存在)    if([[NSFileManager defaultManager] fileExistsAtPath:[self getFilePath]])//之前已经下载    {        //先获取之前文件已经下载了多少        //字典保存文件的信息(由服务器反馈)        NSDictionary *fileDic=[[NSFileManager defaultManager]attributesOfItemAtPath:[self getFilePath] error:nil];        NSLog(@"%@",fileDic);        //获取已接受的文件大小        _receiviceSize=[fileDic[NSFileSize]longLongValue];        //bytes = 0-499 请求前500个字节的内容        //bytes = 500- 请求500字节之后的内容        //bytes = 500-1000 请求资源中某一范围的内容        //bytes = 0-1,499-500 请求多个范围之间的内容        NSString *bytes=[NSString stringWithFormat:@"bytes=%lld-",_receiviceSize];      //设置请求头的Range        [request setValue:bytes forHTTPHeaderField:@"Range"];    }        _connection=[NSURLConnection connectionWithRequest:request delegate:self];}

暂停事件

- (IBAction)pause:(UIButton *)sender {    //取消请求链接    [_connection cancel];    _connection=nil;}

#PRagma mark ---NSURLConnectionDatasource---

//接到响应-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{    //为了获取response里面的StatusCode状态码,将response强转为NSHTTPURLResponse    NSHTTPURLResponse *httpResponse=(NSHTTPURLResponse *)response;    //剩余文件大小    NSDictionary *responseHead=httpResponse.allHeaderFields;    //接收的文件+剩余文件=文件总大小    _totalSize=_receiviceSize+[responseHead[@"Content-Length"]longLongValue];    NSFileManager *manager=[NSFileManager defaultManager];    //如果沙盒中没有该文件就创建文件    if ([manager fileExistsAtPath:[self getFilePath]]==NO) {        [manager createFileAtPath:[self getFilePath] contents:nil attributes:nil];    }    _fileHandle=[NSFileHandle fileHandleForWritingAtPath:[self getFilePath]];}//接到数据-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{    //将光标定位在文件末尾,每次在末位写文件(默认是在文件头部写)    [_fileHandle seekToEndOfFile];    [_fileHandle writeData:data];    //实时更新文件长度    _receiviceSize=_receiviceSize+data.length; }//接收完毕-(void)connectionDidFinishLoading:(NSURLConnection *)connection{    [_fileHandle closeFile];
}
 
 
 
 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表