首页 > 其他 > 详细

2016 - 1- 24 大文件下载 关于NSOutStream 的使用补充

时间:2016-01-24 18:08:45      阅读:379      评论:0      收藏:0      [点我收藏+]
//
//  ViewController.m
//  大文件下载
//
//  Created by Mac on 16/1/24.
//  Copyright © 2016年 Mac. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<NSURLConnectionDataDelegate>

// 输出流
@property (nonatomic, strong) NSOutputStream *stream;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_15.mp4"];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection connectionWithRequest:request delegate:self];
    
}



- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    
    
//    response.suggestedFilename  ------  建议文件名,与服务器上的文件名保持一致
    
    // 获得文件路径
    NSString *str = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *file = [str stringByAppendingString:response.suggestedFilename];
    NSLog(@"%@",file);
    
    // 写入到文件路径,append:YES 表示每次写入都写入当前文件的尾部
    self.stream = [[NSOutputStream alloc] initToFileAtPath:file append:YES];
    
    // 如果文件不存在会自己创建一个新的,注意这一步很重要
    [self.stream open];
    
 
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    
    // 写入文件
    [self.stream write:[data bytes] maxLength:data.length];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    
    // 完成下载,关闭stream
    [self.stream close];
    self.stream = nil;
    NSLog(@"------");
    
}


@end

 

2016 - 1- 24 大文件下载 关于NSOutStream 的使用补充

原文:http://www.cnblogs.com/BJTUzhengli/p/5155362.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!