方法1
// 獲取緩存文件夾
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
// log --> /Users/Mac/Library/Developer/CoreSimulator/Devices/06B6E231-11F9-450B-890C-0B763B210CD9/data/Containers/Data/Application/C59F0A3B-BB35-4F48-BBDF-E750FCBDA02C/Library/Caches
NSLog(@"caches---%@",caches);
// 文件路徑
NSString *file = [caches stringByAppendingPathComponent:@"1233"];
NSLog(@"file---%@",file);
// 創(chuàng)建一個空的文件
[[NSFileManager defaultManager]createFileAtPath:file contents:nil attributes:nil];
// 創(chuàng)建文件句柄
NSFileHandle * fileHandle = [NSFileHandle fileHandleForWritingAtPath:file];
// 指定數(shù)據(jù)的寫入位置-- 文件內(nèi)容的最后面
[fileHandle seekToEndOfFile];
// 寫入數(shù)據(jù)
NSData *data;
[fileHandle writeData:data];
//等待寫入完成后 關(guān)閉handle
[fileHandle closeFile];
fileHandle = nil;
方法2 使用 輸出流NSOutputStream
小知識點(diǎn) response.suggestedFilename :獲取 服務(wù)器那邊的文件名
創(chuàng)建NSOutputStream
// 利用NSOutputStream往Path中寫入數(shù)據(jù)(append為YES的話,每次寫入都是追加到文件尾部)
self.stream = [[NSOutputStream alloc] initToFileAtPath:file append:YES];
// 打開流(如果文件不存在,會自動創(chuàng)建)
[self.stream open];
- 使用NSOutputStream 寫入數(shù)據(jù)
[self.stream write:[data bytes] maxLength:data.length];
NSLog(@"didReceiveData-------");
- 關(guān)閉 NSOutputStream
[self.stream close];
- 代碼如下
#import "ViewController.h"
@interface ViewController () <NSURLConnectionDataDelegate>
/** 輸出流對象 */
@property (nonatomic, strong) NSOutputStream *stream;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]] delegate:self];
}
#pragma mark - <NSURLConnectionDataDelegate>
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// response.suggestedFilename : 服務(wù)器那邊的文件名
// 文件路徑
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename];
NSLog(@"%@", file);
// 利用NSOutputStream往Path中寫入數(shù)據(jù)(append為YES的話,每次寫入都是追加到文件尾部)
self.stream = [[NSOutputStream alloc] initToFileAtPath:file append:YES];
// 打開流(如果文件不存在,會自動創(chuàng)建)
[self.stream open];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.stream write:[data bytes] maxLength:data.length];
NSLog(@"didReceiveData-------");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[self.stream close];
NSLog(@"-------");
}
@end