NSURLConnection大文件下载 NSOutputStream 写入沙盒

#import "ViewController.h"

@interface ViewController () 
/** 输出流对象 */
@property (nonatomic, strong) NSOutputStream *stream;
@end


@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString *urlString = @"http://www.example.com:8080/resources/videos/minion_11.mp4";
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection connectionWithRequest:request delegate:self];
}

#pragma mark - 
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    // response.suggestedFilename : 服务器那边的文件名
    
    // 文件路径
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename];
    NSLog(@"%@", file);
    // /Users/admin/Library/Developer/CoreSimulator/Devices/95A0E48B-2AF9-45A0-83AE-6C065C293B5E/data/Containers/Data/Application/69E9FF35-88C2-41E4-A5EB-51327C22D304/Library/Caches/minion_11.mp4

    
    // 利用 NSOutputStream 往Path中写入数据(append为YES的话,每次写入都是追加到文件尾部)
    self.stream = [[NSOutputStream alloc] initToFileAtPath:file append:YES];
    // 打开流(如果文件不存在,会自动创建)
    [self.stream open];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    NSLog(@"didReceiveData");
    [self.stream write:[data bytes] maxLength:data.length];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"connectionDidFinishLoading");
    [self.stream close];
}

@end

你可能感兴趣的:(NSURLConnection大文件下载 NSOutputStream 写入沙盒)