美文网首页
iOS 文件路径及数据保存

iOS 文件路径及数据保存

作者: 万年老参 | 来源:发表于2022-05-18 16:46 被阅读0次

iOS沙盒路径:
Documents:用于存储用户数据,可被iTunes备份
Library:包含两个子目录
可创建子文件夹。可以用来放置您希望被备份但不希望被用户看到的数据。该路径下的文件夹,除Caches以外,都会被iTunes备份。
Caches:适合存储体积大,不需要备份的非重要数据
Preferences:通常保存应用的设置信息(NSUserDefaults)
tmp:用于存放临时文件,不会被iTunes备份

//document文件夹路径
[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"文件名"]
//temp文件夹路径
 [NSTemporaryDirectory() stringByAppendingPathComponent:@"文件名"]
//cache文件夹路径
 [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"文件名"]
//Libary文件夹路径
 [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"文件名"]

Data保存到沙盒方法:

//以图片保存到沙盒为例:
NSString *patchStr =  [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"图片名字"]
NSData *data = UIImageJPEGRepresentation(image2, 1.0);
BOOL result = [data writeToFile: patchStr atomically:YES];
if (!result) {
        NSLog(@"保存沙盒成功");
}else{
        NSLog(@"保存沙盒失败");
}

图片和视频保存到相册方法:
首先要在plist中添加相册权限获取说明:
在plist中添加Privacy - Photo Library Additions Usage Description , value为提示语
图片及视频保存到相册:

UIImage *image = [UIImage imageNamed:@"imageName"];

UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);

//保存视频
NSString *videoPatch = PATH_AT_Document(@"videoName");
//判断视频是否可保存
if(UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(videoPatch)){
//保存
    UISaveVideoAtPathToSavedPhotosAlbum(videoPatch, self, @selector(videoPatch:didFinishSavingWithError:contextInfo:), nil);
}

//保存回调:
-(void)image:(UIImage*)image didFinishSavingWithError:(id)error contextInfo:(id)info
{
    if (!error) {
        NSLog(@"保存相册成功");
    }else{
        NSLog(@"保存相册失败");
    }
}

-(void)videoPatch:(UIImage*)image didFinishSavingWithError:(id)error contextInfo:(id)info
{
    if (!error) {
        NSLog(@"保存相册成功");
    }else{
        NSLog(@"保存相册失败");
    }
}

相关文章

网友评论

      本文标题:iOS 文件路径及数据保存

      本文链接:https://www.haomeiwen.com/subject/fkmtprtx.html