iOS文件系统---Document

本文介绍了iOS应用程序中Document目录的作用,详细讲解了如何在Document目录下创建、存储视频文件,包括创建文件夹、判断文件是否存在以及从网络下载并保存文件的过程。同时,提到了其他相关目录的功能,如Library用于存储用户偏好设置,tmp用于存放临时数据,而app包则包含开发者资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值