//
// 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
转载于:https://www.cnblogs.com/BJTUzhengli/p/5155362.html
相关资源:JAVA上百实例源码以及开源项目