一 沙盒的机制
沙盒机制是ios中的一种安全机制,沙盒机制的存在使得应用程序之间不能相互访问,保证了数据的安全性.在沙盒里面主要存储了应用的本地缓存,图片,及NSUserDefaults的轻量级数据的存储,而每次程序在启用时,沙盒路径都会发生变化,进一步增加了其安全性.
二 沙盒常见的文件夹及功能
NSArray *doumentlist=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);//通过search找到documents的路径集合
NSString *doupath = doumentlist.lastObject;//取出documents路径
NSLog(@"%@",doumentlist);
NSString *path = NSHomeDirectory();//获取沙盒路径
NSString *dpath = [path stringByAppendingPathComponent:@"Documents"];//通过字符串的路径拼接方法,找到documents路径
//字符串的写入
NSString *strpath = [doupath stringByAppendingString:@"/str.txt"];
NSString *str = @"hellor word!";
[str writeToFile:strpath atomically:YESencoding:NSUTF8StringEncodingerror:nil];
//将图片写入沙盒,首先需要将图片转换成data
UIImage *image = [UIImage imageNamed:@"1.jpg"];
NSData *data2 = UIImageJPEGRepresentation(image, 1);
NSString *phontpath = [doupath stringByAppendingString:@"/photo.jpg"];
[data2 writeToFile:phontpath atomically:YES];
//数组的写入
NSString *arrpath = [doupath stringByAppendingString:@"/arr.plist"];
NSArray *arr = @[@"789",@"456",@"123"];
[arr writeToFile:arrpath atomically:YES];
//字典
NSString *dicpath = [doupath stringByAppendingString:@"/dic.plist"];
NSDictionary *dic = @{@"name":@"zhangsan",
@"sex":@"male"};
[dic writeToFile:dicpath atomically:YES];
//文件操作
NSFileManager *filemanger = [NSFileManagerdefaultManager];//创建文件管理器
NSString *paths = NSHomeDirectory();//获取沙盒路径
NSArray *array = [filemanger contentsOfDirectoryAtPath:paths error:nil];//获取某路径下所有的文件和文件夹(不包含子文件)
NSString *folder = [paths stringByAppendingPathComponent:@"MyFolder"];
BOOL flag = [filemanger createDirectoryAtPath:folder attributes:nil];//创建文件夹,如果该文件夹已存在,则不会创建新的文件夹
BOOL flag2 = [filemanger fileExistsAtPath:folder];//检查文件/文件夹是否存在
NSLog(@"%d",flag2);
BOOL isD;
BOOL flag3 = [filemanger fileExistsAtPath:folder isDirectory:&isD];//判断文件/文件夹是否存在,且该路径是否是文件夹
NSLog(@"flag3 = %d, %d",flag3,isD);
//删除文件/文件夹;
NSString *rpath = [folder stringByAppendingPathComponent:@"3.jpg"];
NSError *err = nil;
BOOL flag4 = [filemanger removeItemAtPath:rpath error:&err];//移除文件/文件夹,注意,如果删除的文件/文件夹不存在,则删除失败
//复制文件
NSString *cPath = [folder stringByAppendingPathComponent:@"3.jpg"];
NSString *newPath = [path stringByAppendingPathComponent:@"Documents/3.png"];
if ([filemanger fileExistsAtPath:rpath]) {
NSLog(@"文件存在");
NSError *err1 = nil;
BOOL flag5 = [filemanger copyItemAtPath:cPath toPath:newPath error:&err1];//文件拷贝,注意:1、atPath(源文件)必须存在,toPath(目标文件) 必须不存在,如果toPath已经存在,则复制失败 2、atPath(源文件)以及toPath(目标文件),这两个参数必须是完整的文件路径(不考虑后缀名),不能只写到文件夹
NSLog(@"%d,%@",flag5,err1);
}
//移动文件
NSString *mPath = [folder stringByAppendingPathComponent:@"2.jpg"];
NSString *newMPath = [path stringByAppendingPathComponent:@"Documents/4.png"];
[filemanger moveItemAtPath:mPath toPath:newMPath error:nil];//文件移动,注意:1、atPath(源文件)必须存在,toPath(目标文件) 必须不存在,如果toPath已经存在,则移动失败; 2、atPath(源文件)以及toPath(目标文件),这两个参数必须是完整的文件路径(不考虑后缀名),不能只写到文件夹; 3、移动成功后,源文件消失
returnYES;
四 开发例子
NSMutableArray *inputPaths=[NSMutableArray array];
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *createPath = [NSString stringWithFormat:@"%@/Image", pathDocuments];
// 判断文件夹是否存在,如果不存在,则创建
if (![[NSFileManager defaultManager] fileExistsAtPath:createPath]) {
[fileManager createDirectoryAtPath:createPath withIntermediateDirectories:YES attributes:nil error:nil];
}
for (int i=0; i<_vc.itemsSectionPictureArray.count; i++)
{
UIImage *image=_vc.itemsSectionPictureArray[i];
CGSize imagesize = image.size;
imagesize.height =768;
imagesize.width =768/(image.size.height/image.size.width);
//对图片大小进行压缩--
image = [self imageWithImage:image scaledToSize:imagesize];
NSString *filePath = [createPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%dlcx.jpg",i]]; // 保存文件的名称
[inputPaths addObject:filePath];
[UIImageJPEGRepresentation(image,0.85) writeToFile:filePath atomically:YES];
//NSData *data = UIImageJPEGRepresentation(image,0.85);
}
NSString *zippedPath=[NSString stringWithFormat:@"%@/wzg.zip",NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject] ;
NSLog(@"%@",zippedPath);
//[SSZipArchive createZipFileAtPath:zippedPath withFilesAtPaths:inputPaths];
if ([SSZipArchive createZipFileAtPath:zippedPath withFilesAtPaths:inputPaths]) {
NSLog(@"压缩成功");
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// 在网络开发中,上传文件时,是文件不允许被覆盖,文件重名
// 要解决此问题,
// 可以在上传时使用当前的系统事件作为文件名
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 设置时间格式
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@.zip", str];
//formData: 专门用于拼接需要上传的数据,在此位置生成一个要上传的数据体
[manager POST:strUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
NSData *mydata = [NSData dataWithContentsOfFile:zippedPath];
[formData appendPartWithFileData:mydata name:@"sourceImg1" fileName:fileName mimeType:@"application/zip"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"-------上传成功 %@", responseObject);
if (self.type==0||self.type==1||self.type==2) {
self.valueBlock();
}
[fileManager createDirectoryAtPath:createPath withIntermediateDirectories:YES attributes:nil error:nil];
[fileManager removeItemAtPath:createPath error:nil];
[fileManager removeItemAtPath:zippedPath error:nil];
NSUserDefaults *mySettingData = [NSUserDefaults standardUserDefaults];
[mySettingData removeObjectForKey:@"ATMquanzicontent"];
[mySettingData synchronize];
//self.view.alpha=1;
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"上传失败" message:@"操作超时,请重试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil,nil];
[alert show];
NSLog(@"%@",error);
//self.view.alpha=1;
//[_mbprogreeHUD removeFromSuperview];
//self.valueBlock(error);
}];
}
else {
}
});
}