iOS 沙盒存储文档,图片

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

typedef NS_ENUM(NSUInteger, FileNmae) {
    FileNmaeDocuments,
    FileNmaeLibrary,
    FileNmaeTemp,
    FileNmaeHome,
};

@interface FileManager : NSObject


/**
 初始化方法
 @param dirPath 文件夹名字 可以为 nil
 @param fileName 文件名
 @param extensionName 扩展名
 @return <#return value description#>
 */
- (instancetype)initWithDirPath:(NSString *)dirPath fileName:(NSString *)fileName extensionName:(NSString *)extensionName;
/** 完整路径  */
- (NSString *) getAllPaht;
#pragma mark ----------------------- 文件管理 ------------------------
/**  创建文件夹  */
- (void)createDir;
/**  创建文件  */
- (void)createFile;
/**  删除文件  */
- (void)deleteFile;
/**  查看文件夹下文件列表  */
- (NSArray *)lookDir;
/**  删除文件夹  */
- (void)delDir;
/**  清空文件夹下所有内容  */
- (void)delDirDetail;
#pragma mark ----------------------- 文档 ------------------------
/**  读取文件  */
- (NSString *)readFileContent;
/**  写入文件  */
- (void)writeFile:(NSString *)content;
#pragma mark ----------------------- 图片 ------------------------
/** 图片  */
- (void)saveImageDocuments:(UIImage *)image;
/**  读取图片  */
- (UIImage *)getDocumentImage;

+ (NSString *)getNowTimestamp;

@end
#import "FileManager.h"

@interface  FileManager ()

@property(nonatomic,copy)NSString *fileName;
@property(nonatomic,copy)NSString *extensionName;
@property(nonatomic,copy)NSString *dirPath;

@end

@implementation FileManager

- (instancetype)initWithDirPath:(NSString *)dirPath fileName:(NSString *)fileName extensionName:(NSString *)extensionName
{
    self = [super init];
    if (self) {
        self.dirPath = dirPath;
        self.fileName = fileName;
        self.extensionName = extensionName;
    }
    return self;
}

#pragma mark ----------------------- 获取文件全名 ------------------------
-(NSString *)getAllName{
    return [NSString stringWithFormat:@"%@.%@",self.fileName,self.extensionName];
}

#pragma mark ----------------------- 获取文件路径 ------------------------
- (NSString *)getFilePathFromNmae:(FileNmae)fileNmae
{
    NSString *paths;
    if (fileNmae == FileNmaeDocuments)
    {
         paths = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    }
    else   if (fileNmae == FileNmaeLibrary)
    {
        paths = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
    }
    else   if (fileNmae == FileNmaeTemp)
    {
        paths = NSTemporaryDirectory();
    }
    else   if (fileNmae == FileNmaeHome)
    {
        paths = NSHomeDirectory();
    }
    return paths;
}

#pragma mark ----------------------- 添加子目录 ------------------------
-(NSString *) getAllPaht
{
    NSString * docsdir = [self getFilePathFromNmae:(FileNmaeDocuments)];
    NSString *dataFilePath = [docsdir stringByAppendingPathComponent:self.dirPath]; // 在Document目录下创建 "archiver" 文件夹
    return dataFilePath;
}

#pragma mark ----------------------- 创建文件夹 ------------------------
- (void)createDir
{
    NSString *dataFilePath = [self getAllPaht];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = [self isDirExist:dataFilePath];
    if (!isDir) {
        // 在Document目录下创建一个wenjian目录
        [fileManager createDirectoryAtPath:dataFilePath withIntermediateDirectories:YES attributes:nil error:nil];
        
    }
    
}

#pragma mark ----------------------- 创建文件 ------------------------
-(void)createFile
{
    NSString *documentsPath =[self getAllPaht];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *iOSPath = [documentsPath stringByAppendingPathComponent:[self getAllName]];
    // 判断该路径文件是否存在
    BOOL isHave = [self isSxistAtPath:iOSPath];
    
    if (!isHave)
    {
        BOOL isSuccess = [fileManager createFileAtPath:iOSPath contents:nil attributes:nil];
        if (isSuccess)
        {
            NSLog(@"创建文件成功");
        }
        else
        {
            NSLog(@"文件已经存在");
        }
    }
}


#pragma mark ----------------------- 写文件 ------------------------
-(void)writeFile:(NSString *)content
{
    NSString *documentsPath = [self getAllPaht];
    NSString *iOSPath = [documentsPath stringByAppendingPathComponent:[self getAllName]];
    BOOL isSuccess = [content writeToFile:iOSPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    if (isSuccess)
    {
        NSLog(@"读取成功");
        
    }
    else
    {
        NSLog(@"读取失败");
        
    }
}


#pragma mark ----------------------- 读取文件 ------------------------
-(NSString *)readFileContent
{
    NSString *documentsPath = [self getAllPaht];
    NSString *iOSPath = [documentsPath stringByAppendingPathComponent:[self getAllName]];
//    BOOL isHave = [self isSxistAtPath:iOSPath];
    
    NSString *content = [NSString stringWithContentsOfFile:iOSPath encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"文件内容 = \n%@",content);
    return content;
}

#pragma mark ----------------------- 删除文件 ------------------------
-(void)deleteFile
{
    NSString *documentsPath =[self getAllPaht];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *iOSPath = [documentsPath stringByAppendingPathComponent:[self getAllName]];
    
    BOOL isSuccess = [fileManager removeItemAtPath:iOSPath error:nil];
    if (isSuccess)
    {
        NSLog(@"删除成功");
    }
    else
    {
        NSLog(@"删除失败");
    }

}

#pragma mark ----------------------- 判断文件是否存在 ------------------------
- (BOOL)isSxistAtPath:(NSString *)filePath
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isExist = [fileManager fileExistsAtPath:filePath];
    if (isExist)
    {
        NSLog(@"文件存在");
    }
    else
    {
        NSLog(@"文件不存在");
    }
    return isExist;
}


#pragma mark ----------------------- 判断路径(文件夹)是否存在 ------------------------
- (BOOL)isDirExist:(NSString *)path
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = NO;
    BOOL isDirExist = [fileManager fileExistsAtPath:path isDirectory:&isDir];
    
    BOOL isHave = (isDirExist && isDir);
    
    if (isHave)
    {
        NSLog(@"文件夹存在");
    }
    else
    {
        NSLog(@"文件夹不存在");
    }
    return  isHave;
}

-(NSArray *)lookDir
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //在这里获取应用程序Documents文件夹里的文件及文件夹列表

    NSString *documentDir = [self getAllPaht];
    NSError *error = nil;
    NSArray *fileList = [[NSArray alloc] init];
    //fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
    fileList = [fileManager contentsOfDirectoryAtPath:documentDir error:&error];
    
    //以下这段代码则可以列出给定一个文件夹里的所有子文件夹名
    NSMutableArray *dirArray = [[NSMutableArray alloc] init];
    BOOL isDir = NO;
    //在上面那段程序中获得的fileList中列出文件夹名
    for (NSString *file in fileList) {
        NSString *path = [documentDir stringByAppendingPathComponent:file];
        [fileManager fileExistsAtPath:path isDirectory:(&isDir)];
        if (isDir) {
            [dirArray addObject:file];
        }
        isDir = NO;
    }
    NSLog(@"Every Thing in the dir:%@",fileList);
    return fileList;
//    NSLog(@"All folders:%@",dirArray);
}

#pragma mark ----------------------- 删除文件夹 ------------------------
-(void)delDir
{
    
    NSString *documentDir = [self getFilePathFromNmae:(FileNmaeDocuments)];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager removeItemAtPath:documentDir error:NULL])
    {
        NSLog(@"Removed successfully");
    }
}


#pragma mark ----------------------- 删除文件夹下所有内容 ------------------------
-(void)delDirDetail
{
    NSString *string = [self getFilePathFromNmae:(FileNmaeDocuments)];
    NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:string];
    for (NSString *fileName in enumerator)
    {
        [[NSFileManager defaultManager] removeItemAtPath:[string stringByAppendingPathComponent:fileName] error:nil];
    }
    
}

#pragma mark ----------------------- 保存图片 ------------------------
-(void)saveImageDocuments:(UIImage *)image
{

//    //拿到图片
//    //设置一个图片的存储路径
//    NSString *imagePath = [NSString stringWithFormat:@"%@/%@.%@",[self getAllPaht],self.fileName,self.extensionName];
//    //把图片直接保存到指定的路径(同时应该把图片的路径imagePath存起来,下次就可以直接用来取)
//    [UIImagePNGRepresentation(image) writeToFile:imagePath atomically:YES];
    
    [self writeFile:[self imageToString:image]];
    

    
}


// 读取并存贮到相册

-(UIImage *)getDocumentImage{
//    // 读取沙盒路径图片
//    NSString *imagePath = [NSString stringWithFormat:@"%@/%@.%@",[self getAllPaht],self.fileName,self.extensionName];
//    // 拿到沙盒路径图片
//    UIImage *imgFromUrl3=[[UIImage alloc]initWithContentsOfFile:imagePath];
//    // 图片保存相册
//    UIImageWriteToSavedPhotosAlbum(imgFromUrl3, self, nil, nil);
    
//    return imgFromUrl3;
    
   return  [self stringToImage:[self readFileContent]];
}


#pragma mark ----------------------- iamge 转 base64  ------------------------
- (NSString *)imageToString:(UIImage *)image {
    
    NSData *imagedata = UIImagePNGRepresentation(image);
    
    NSString *image64 = [imagedata base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    return image64;
    
}

#pragma mark ----------------------- base64 转 image  ------------------------
- (UIImage *)stringToImage:(NSString *)str {
    
    NSData * imageData =[[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
    
    UIImage *photo = [UIImage imageWithData:imageData ];
    
    return photo;
    
}


+(NSString *)getNowTimestamp
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    //设置时区,这个对于时间的处理有时很重要
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];//现在时间
    NSLog(@"设备当前的时间:%@",[formatter stringFromDate:datenow]);
    //时间转时间戳的方法:
    NSInteger timeSp = [[NSNumber numberWithDouble:[datenow timeIntervalSince1970]] integerValue];
    NSLog(@"设备当前的时间戳:%ld",(long)timeSp); //时间戳的值
    NSString *str = [NSString stringWithFormat:@"%ld",(long)timeSp];
    return str;
}
    
    






@end

#import "ViewController.h"
#import "FileManager.h"

@interface ViewController ()
<
UINavigationControllerDelegate,
UIImagePickerControllerDelegate
>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    FileManager * f = [[FileManager alloc]initWithDirPath:@"wenjian" fileName:@"iOS" extensionName:@"h"];
    
    NSLog(@"\n%@\n", [f getAllPaht]);
    
    [f createDir];
    [f lookDir];

//    [f createFile];
    
//    [f readFileContent];
//    NSDictionary *dataDict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Property List" ofType:@"plist"]];
//    [f writeFile:[dataDict valueForKey:@"h"]];
//    [f readFileContent];
//    [f lookDir];
    
    
//    [f delDir];
//    [f delDirDetail];
//    [f lookDir];
    
    

//    NSLog(@"\n--------------->>>>>>---------------\n%@ \n---------------<<<<<<<<<<<---------------\n",);
    
    
    
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UIImagePickerController * picker = [[UIImagePickerController alloc]init];
    UIImagePickerControllerSourceType sourcheType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.sourceType = sourcheType;
    picker.delegate = self;
    picker.allowsEditing = NO;
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary)
    {
        if ([info valueForKey:UIImagePickerControllerOriginalImage])
        {
            UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage]; //原始图片
            //处理图片信息`info` ...
            
            FileManager * f = [[FileManager alloc]initWithDirPath:@"wenjian" fileName:[FileManager getNowTimestamp] extensionName:@"png"];
            [f saveImageDocuments:image];
            
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
            
            imageView.image = [f getDocumentImage];
            [self.view addSubview:imageView];
            
            [f lookDir];
        }
        else
        {
            //处理视频信息 `info` ...
            NSLog(@"视频URL是:%@",[info valueForKey:UIImagePickerControllerMediaURL]);
        }
    }
    else
    {
        if (picker.cameraCaptureMode == UIImagePickerControllerCameraCaptureModeVideo)
        {
            //处理视频信息 `info`
            NSLog(@"视频URL是:%@",[info valueForKey:UIImagePickerControllerMediaURL]);
        }
        else
        {
            UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage]; //原始图片
            //处理图片信息`info`   ...
        }
    }
//    NSLog(@"%@",info.description);
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end


猜你喜欢

转载自blog.csdn.net/saw471/article/details/81044970
今日推荐