iOS文件操作

本文详细介绍如何在iOS应用中实现文件的下载、存储及管理。包括视频和图片的下载到指定目录,将字典、字符串、数组等数据写入本地文件,并介绍了如何计算文件大小、清理缓存以及从app包中读取资源。

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

**首先我们需要了解苹果的沙盒机制

沙盒机制:
1.每个应用程序都在自己的沙盒内
2.不能随意跨越自己的沙盒去访问别的应用程序沙盒的内容
3.应用程序向外请求或接收数据都需要经过权限认证

当第一次启动app 时,ios操作系统就为此app 创建一个文件系统,该文件系统下,默认有四个目录,他们分别是:**

**1. DoucumnetS:用户在操作APP是产生的数据,在此目录下的数据可以跟icloud同步
- library:用户偏好设置的,通常和此类的NSUserDefaults搭配使用,在此目录下的数据可以和 icloud同步
- tmp:此目录下的数据是存放临时数据的,在此目录下的数据不会通过icould同步
- app包:开发者不会操作此目录,通常是通过此类NSBundle来获取包内资源,如工程素材**

好了,我们废话不多说,马上上代码

//    获取程序的根目录
    NSString *rootPath = NSHomeDirectory();
//    获取根目录下的Documents
    NSString *documentsString = [rootPath stringByAppendingPathComponent:@"Documents"];

或者换另外一种写法获取根目录下的Documents

documentsString = [rootPath stringByAppendingFormat:@"/Documents"];

最常用的获取Documents目录的方式


//   NSArray *array =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES);
//   documentsString =  [array lastObject];

    documentsString = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES)objectAtIndex:0];

一、下载视频
1.把一段视频下载到Documents目录下的Video文件夹里面
首先我们写一个方法用来创建一个Video文件夹

-(NSString *)creatDirInDocuments:(NSString *)dirName{

//    获取Document的文件路径

    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];

//    拼接成我们想要的文件的路径的字符串
    NSString *dirDocuments = [documentPath stringByAppendingPathComponent:dirName];

//    创建一个NSFileManager单例类的对象,用于文件操作
    NSFileManager *fileManager = [NSFileManager defaultManager];

//    判断本地是否纯在这个文件
    BOOL isExist = [fileManager fileExistsAtPath:dirDocuments];
    if (isExist) {
//        如果不存在就创建
        NSError *error ;//创建一个错误
        BOOL isSuccess = [fileManager createDirectoryAtPath:documentPath withIntermediateDirectories:YES attributes:nil error:&error];

        if (!isSuccess) {
            NSLog(@"error = %@",error.debugDescription);//如果文件创建失败,将错误信息打印
            dirDocuments = nil;
        }
    }

    return dirDocuments;

}

2.调用刚刚写好的那个方法,对视频进行下载

//    调用方法创建Video文件夹
    NSString *videoPath = [self creatDirInDocuments:@"Video"];
    if (videoPath != nil ) {
//        拿到视频的URL
        NSString *videoUrlString = @"http://211.162.52.225/mp4files/41080000030BAD66/120.198.231.208/211.136.10.55/videoplayer/h0199okmjft.p701.1.mp4";
        NSString *filePath = [videoPath stringByAppendingPathComponent:[videoUrlString lastPathComponent]];

//        创建单例类NSFileManager对象,并且判断
        NSFileManager *fileManager = [NSFileManager defaultManager];

        if (![fileManager isExecutableFileAtPath:filePath]) {
//            NSData *data = nil;
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:videoUrlString]];
            if ([fileManager createFileAtPath:filePath contents:data attributes:nil]) {
                NSLog(@"视频下载成功");
            }else{
                NSLog(@"视频下载失败");
            }
        }
    }


3.然后打个断点拿到视频下载好所保存的路径
这里写图片描述
4.然后复制这个路径,打开我们的Finder 然后Command + shift + G
这里写图片描述
5.把我们复制到的路径粘贴,然后点击前往
这里写图片描述
6.就能找到我们刚刚下载的视频
这里写图片描述
7.我们播放试试看..
这里写图片描述
8.谭咏麟的<一生中最爱>完美播放
这里写图片描述

二、下载图片
1.下载图片到我们的Tmp的image文件夹中
1.1和下载视频类似,先写一个方法来创建image文件夹


-(NSString *)CreatDirTemp:(NSString *)dirName{
//    获取temp的文件路径

    NSString *tempPath = NSTemporaryDirectory();
//    想要文件夹的路径
    NSString *dirPath = [tempPath stringByAppendingPathComponent:dirName];

    NSFileManager *flieManger = [NSFileManager defaultManager];
    if (![flieManger fileExistsAtPath:dirPath]) {
        NSError *error ;
        BOOL isSucess = [flieManger createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:&error];
        if (!isSucess) {
            NSLog(@"%@",error.debugDescription);
            dirPath = nil;
        }
    }
    return dirPath;

2.跟下载视频一样,调用刚刚写的方法

 NSString *tempString = NSTemporaryDirectory();
    NSString *imageDocumentsPath = [self creatDirInTemp:@"image"];

//    用数组保存图片的URL
    NSArray *imgArray = @[@"http://photocdn.sohu.com/20160401/Img443057535.jpg",@"http://house.jschina.com.cn/userfiles/image/20140609/0918085077d94d4b2a0375.jpg",@"http://uface.56img.com/photo/57/94/r431124892_b_56.com_.jpg",@"http://img5q.duitang.com/uploads/item/201407/20/20140720111830_jAcaV.jpeg",@"http://image.tianjimedia.com/uploadImages/2013/319/Z1J940LY8B2T.jpg",@"http://img.wanchezhijia.com/A/2015/1/27/b8d4f1fd-ddaf-4d1b-958b-77f88e1a8ff4.jpg"];

    if (imageDocumentsPath != nil) {
        for (id obj in imgArray) {
            NSString *imgString = [obj lastPathComponent];
//            获得每一张图片的路径
            NSString *imagePath = [imageDocumentsPath stringByAppendingPathComponent:imgString];
            NSFileManager *fileManager = [NSFileManager defaultManager];
            if (![fileManager fileExistsAtPath:imagePath]) {
//                将每一张图片进行编码
                NSString *urlString = [obj stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//                下载图片,拿到网址图片的data
                NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
                if (data == nil) {
                    NSLog(@"网络有问题,请稍后再下载");
                }else{
                    if ([data writeToFile:imagePath atomically:YES]) {
                        NSLog(@"图片下载成功");
                    }else{

                        NSLog(@"图片下载失败");
                    }
                }

            }
        }
    }

3.然后打个断点po一下拿到imgage这个文件夹的路径
这里写图片描述
4.还是像查找视频那样查找文件夹里面是否存在有所下载的文件,这里就不一一贴图出来了,不会再参考上面的是视频是怎么找到的
这里写图片描述

三、将字典、字符串、数组写入本地

//    将字符串写入到本地
    NSString *str = @"我是你转身就忘的路人甲,凭什么陪你蹉跎年华到天涯?";
    if ([str writeToFile:[imageDocumentsPath stringByAppendingPathComponent:@"a.txt"] atomically:YES encoding:NSUTF8StringEncoding error:nil]) {
        NSLog(@"字符串写入成功");
    }else{
        NSLog(@"字符串写入失败");
    }


//    将数组写入本地
    NSArray *array = @[@"暴走大事件",@"王尼玛",@"张全蛋",@"赵铁根"];
    if ([array writeToFile:[imageDocumentsPath stringByAppendingPathComponent:@"B.txt"] atomically:YES]) {
        NSLog(@"数组写入成功");
    }else{
        NSLog(@"数组写入失败");
    }


//    将字典写入本地
    NSDictionary *dict = @{@"name":@"王尼玛",@"age":@"28",@"address":@"SZ",@"hobby":@"暴走大事件"};
    if ([dict writeToFile:[imageDocumentsPath stringByAppendingPathComponent:@"D.txt"] atomically:YES]) {
        NSLog(@"字典写入成功");
    }else{

        NSLog(@"字典写入失败");
    }

查找成功写入本地的文件
这里写图片描述

四、计算文件的大小

//    计算文件夹的大小
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *fileManagerArray = [fileManager subpathsAtPath:imageDocumentsPath];

输出结果如下:
这里写图片描述

五、遍历、以及清除缓存、获取app包里面的图片显示在UI上
1.打开Main.storyboard,拖拽一个UIimageView控件,然后连接在我们的ViewController控制器上,并且把UIimageView设置为属性
这里写图片描述

这里写图片描述



//    遍历
    CGFloat count = 0.0;
    for (id obj in fileManagerArray) {
        NSData *data = [NSData dataWithContentsOfFile:[imgDocumentsPath stringByAppendingPathComponent:obj]];
        count += data.length;

    }
    count = count/1024/1024;
    NSLog(@"缓存文件的大小为:%.2fM",count);

#pragma mark 删除文件
    for (id obj in fileManagerArray) {

        if ([fileManager removeItemAtPath:[imgDocumentsPath stringByAppendingPathComponent:obj] error:nil]) {
            NSLog(@"删除成功!!!");
        }
        else{
            NSLog(@"删除失败!!!");
        }

    }

//    app包,获取包内的图片,显示在UI上

   NSData *imgData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"555" ofType:@".jpg"]];

    self.picImageView.image = [UIImage imageWithData:imgData];

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值