网络(下载)

作者: 郭大猿 | 来源:发表于2016-01-24 00:49 被阅读53次

    准备:

    NSString *urlString = @"http://127.0.0.1/dawenjian.zip";
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    

    1.NSURLConnection:异步回调下载

    • 发送 GET 请求
    // 同步:localResponse 为 nil,用来接受本地请求返回的响应。
    [NSURLConnection sendSynchronousRequest:localRequest returningResponse:&localResponse error:NULL];
    
    // 异步
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
      NSLog(@"response:%@",response);
        }];
        
    
    
    
    • NSURLConnectionDownloadDelegate:3个代理方法
      1. 做下载进度条使用。
      2. 只能坚挺下载进度,但文件下载完成之后找不到下载文件
    //  设置 NSConnection 代理
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    @optional
    1. // 检测下载过程(下载进度条使用!)//多次调用的下载方法!
    // bytesWritten: 本次下载(本次调用这个方法)写入(下载)的数据量
    // totalBytesWritten :目前为止,已经写入(下载)的数据总量
    // expectedTotalBytes: 需要下载的文件的大小(需要写入的总数据量)
    - (void)connection:(NSURLConnection *)connection didWriteData:(long long)bytesWritten totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long) expectedTotalBytes;
    
    2. // 断点续传的方法,没用。
    - (void)connectionDidResumeDownloading:(NSURLConnection *)connection totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long) expectedTotalBytes;
    
    @required
    3. // 下载完成之后,调用的方法!
    // destinationURL:网络下载完成之后,文件存储的路径!
    // destinationURL:网络下载完成之后,文件存储的路径!
    - (void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *) destinationURL;
    
    
    • NSURLConnectionDataDelegate
    1. // 接收到服务器响应的时候,就会调用!
    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
    
    2. // 开始接受服务器响应的数据的时候就会调用
    // 多次调用,每次下载一点数据,直到数据下载完毕!
    // data : 本次下载接受的数据!
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
    
    3. // 下载完成之后,就会调用!
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection;
    {
    
    
      • (void)start; 开始连接
      • (void)cancel; 取消连接

    2.NSFileHandle:句柄,在下载文件过程中,内存没有飙升

    
    // 开始接受数据的时候会调用
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
        //创建句柄
        NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:self.filePath];
        if (fileHandle) {
            //把句柄移动到文件末尾
            [fileHandle seekToEndOfFile];
            [fileHandle writeData:data];
        }else{
        //当路径下边还没有 文件的时候调用
            [data writeToFile:self.filePath atomically:YES];
        }
        NSLog(@"data.length%ld",data.length);
    }
    
    

    3.HEAD:只获取响应头信息,不要实体内容.但是!!!这个方法会重新加载本地文件到内存中,由加载的文件大小决定线程卡住的时间

    
    // 因为HEAD请求,只获取响应头信息,数据量比较少,所以一般使用同步方法发送!
    // 在下载大文件之前,需要获得文件信息之后,由用户做出判断之后在再下载.
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"HEAD";
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {        
            //需要下载的文件长度:
            long long serverFileLength = response.expectedContentLength;
    }
    

    4.NSFileManager

    1. NSFileManager 主要对文件进行管理, 具有:创建文件,复制文件,删除文件,剪切文件的功能。
    2. NSFileManager 为单例,不能用 alloc 创建:
    //创建 NSFileManager 对象
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    
    1. 常用方法:
    //创建一个⽂件并写入数据
    - (BOOL)createFileAtPath:(NSString *)path contents:(NSData *)data attributes:(NSDictionary *)attr;
    //从⼀个文件中读取数据
    - (NSData *)contentsAtPath:(NSString *)path;
    //srcPath路径上的⽂件移动到 dstPath 路径上, 注意这里的路径是⽂件路径⽽不是目录
    - (BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error;
    //srcPath路径上的文件复制到 dstPath 路径上
    - (BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error;
    //文件是否存在
    - (BOOL)fileExistsAtPath:(NSString *)path;
    // 移除⽂件
    - (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error;
    
    
    1. 创建文件:
    //创建 NSFileManager 对象
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *homePath = NSHomeDirectory();
    NSString *path = [homePath stringByAppendingPathComponent:@"file.txt"];
    NSString *text = @"docoder";
    //将字符串转成NSData类型
    NSData *data = 1;
    //写⼊文件
    BOOL success = [fileManager createFileAtPath:path contents:data attributes:nil];
    
    
    1. 读取文件
    //创建 NSFileManager 对象
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //根据路径读取文件
    NSData *fileData = [fileManager contentsAtPath:filePath];
    //将NSData转NSString
    NSString *content = [[NSString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
    
    1. 剪切、复制
    
    NSString *homePath = NSHomeDirectory();
    //源⽂件路径
    NSString *srcPath = [homePath stringByAppendingPathComponent:@"file.txt"];
    //目标路径
    NSString *toPath = [homePath stringByAppendingPathComponent:@"Documents/file.txt"];
    
    
      NSError *error;
      //剪切(移动)文件
      //将srcPath路径的文件剪切(移动)到toPath路径
      BOOL isSuccess = [fm moveItemAtPath:srcPath toPath:toPath error:&error];
      if(!isSuccess){
          NSLog(@"失败:%@",error);
      }
      //复制文件
      //将srcPath路径的⽂件复制到toPath路径
      BOOL success = [fm copyItemAtPath:srcPath toPath:toPath error:nil];
        
    
    1. 删除文件
    //判断⽂件是否存在
    BOOL isExist = [fm fileExistsAtPath: path];
    if (isExist) {
      //删除⽂件
      BOOL success = [fm removeItemAtPath:path error:nil];
      if (success) {
          NSLog(@"remove success");
      }
    }
    
    

    8.获取文件大小

    1. 通过读取文件属性获得:
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //获得文件的属性字典
    NSDictionary *attrDic = [fileManager attributesOfItemAtPath:path error:nil];
    //获取⽂件⼤小
    NSNumber *fileSize = [attrDic objectForKey:NSFileSize];
    
    2. 计算获得 (此方法如果读取大文件会很占有内存,不建议使用):
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSData *data = [fileManager contentsAtPath:path];
    NSInteger len=data.length;
    
    
    

    9.断点续传

    • 设置请求头信息(User-Agent; Content-Type ;Range)

    • Range: 告诉服务器,本次请求(想要获得的数据)从哪里开始,取多少数据...

    • 设置 Range 头信息:

      1. Bytes=x-y: 从第x个字节开始,下载y个字节!
      2. Bytes=0- : 从第0个字节开始,下载到结束!
      3. Bytes=x- :从第x个字节开始,下载结束!
    • 断点续传格式
      NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
      // 设置断点续传信息
      NSString *range = [NSString stringWithFormat:@"Bytes=%lld-%lld",startSize,endSize];
      [request setValue:range forHTTPHeaderField:@"Range"];
      

    相关文章

      网友评论

      • 郭大猿:这里简单介绍了平时用到的几种方法,主要是记录下学习的过程,如果大家有什么不明白的地方,或者感觉哪里写的不够详细可以给我评论,在以后的笔记中我会更加改进的。

      本文标题:网络(下载)

      本文链接:https://www.haomeiwen.com/subject/aeprkttx.html