#import "ViewController.h"
@interface ViewController () <NSURLConnectionDataDelegate>
/** 输出流对象 */
@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 - <NSURLConnectionDataDelegate>
- (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 写入沙盒
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 使用delegate的方式: <NSURLConnectionDataDelegate>相关代理方法实现: 如果要...
- 前言: 出于安全考虑,iOS系统的沙盒机制规定每个应用都只能访问当前沙盒目录下面的文件(也有例外,比如系统通讯录能...
- 前言: 出于安全考虑,iOS系统的沙盒机制规定每个应用都只能访问当前沙盒目录下面的文件(也有例外,比如系统通讯录能...