iOS文件系统
当第一次启动app的时候,iOS操作系统就为此APP创建一个文件系统,该文件系统下默认有四个目录,
分别是:
Document:存储用户在操作app时产生的数据,在此目录下的数据可以通过iCloud进行同步
Library:用户偏好设置,通常和 NSUserDefaults 搭配使用,在此目录下的数据可以通过iCloud进行同步
tmp: 存放临时数据,此目录下的数据不会通过iCloud进行同步
app包:开发者不会开发此目录,通常是通过NSBundle来获取包内资源,如工程素材
1Document
//获取程序的根目录
NSString *rootPath=NSHomeDirectory();
运行结果:
/Users/ibokan/Library/Developer/CoreSimulator/Devices/B2770488-8D05-4BA9-A598-7E95B4365D1C/data/Containers/Data/Application/535EF763-AD18-4DAE-977A-1D906C19DB57
//这是文件的一个路径
//获取根目录下的Documents
NSString *documentPath= [rootPath stringByAppendingPathComponent:@"Documents"];(自动生成下划线)
//最常用的获取Documents的目录方式
//NSUserDomainMask=1;
NSArray *array= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES);
documentPath= [array objectAtIndex:0];
//返回的是数组类型,而且数组只有一个元素,所以直接访问第一个元素就可以了
//最终写法:
documentPath= [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES) objectAtIndex:0];
下载一个视频文件,放在Documents目录下的Video文件
思路:
1.在Documents目录下创建Video文件,也就是编写一个创建文件夹方法
(找到Documents目录 , 将Video文件拼接上 , 进行判断文件是否存在 , 如果不存在,那么就用NSFileManager进行创建文件夹)
-(NSString *)createDirInDocuments:(NNString *)videoName{
NSString *dirDocuments=[NSSearchPathFOrDirectoriesInDocuments(NSDocumentDirectory,1,YES) objectAtIndex:0];
NSString *dirVideoPath=[dirDocuments stringByAppendingPathComponent:videoName];
//判断文件是否存在,需用要到单例NSFileManager的对象进行判断
NSFileManager *fileManager=[NSFileManager defaultManager];
Bool isExist=[fileManager fileExistsAtPath:dirVideoPath];
if(!isExist){
NSError *error;
Bool isSuccess= [fileManager createDirectoryAtPath:dirVideoPath withIntermediateDirectories:YES attributes:nil error:&error];
if(!isSuccess){
NSlog(@"error=%@",error.debugDescription);
dirVideoPath=nil;
}
}
return dirVideoPath;
}
2.将视频传入到Video文件中
(先运用上面的方法创建文件夹 , 然后进行文件夹判断是否为空 假设不为空的话, 就将视频的路径写入文件夹中 接着判断该文件夹是否存在该路径 假设不存在 就从网络上读取文件(文件类型用NSDate接收) 然后用NSFileManager的对象将文件写入本地 最后判断时候写入成功)
NSString *videpath=[self createDirInDocuments:@"Video"]
if(videoPath!=nil){
NSString *videUrlString=@"(网上下载的mp4)";
NSString *filePath=[videPath stringByAppendingComponent:[videUrlString lastPathComponent]];
NSFileManager *fileManager=[NSFileManager defaultManager];
if(![fileManager fileExistAtPath:filePath]){
NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:videUrlString]];
//用NSFileManager的对象 将文件写入本地
Bool isSuccess=[fileManager createFileAtPath:filePath contents:data attributes:nil];
if(isSuccess){
NSLog(@"视频下载成功");
}
else{
NSLpg(@"视频下载失败");
}
}
}
注意:
1.进行判断文件以及文件夹是否存在 , 是为了防止之前就存在相同的文件
2.计算机文件分为二进制与文本文件 , 而视频文件为二进制 , 所以用NSDate