美文网首页
iOS -- 本地存储图片和沙盒机制

iOS -- 本地存储图片和沙盒机制

作者: 恋空K | 来源:发表于2018-11-08 14:49 被阅读12次

    先上本地存储图片的代码:

    - (void)viewDidLoad {

        [super viewDidLoad];

        self.view.backgroundColor = [UIColor redColor];

        NSString *filePath = [self getFilePathWithImageName:@"good_coupon_bg"];

        BOOLisExist = [selfisFileExistWithFilePath:filePath];

        if (!isExist){ // 如果该图片不存在,则删除老图片,下载新图片

            [self downloadAdImageWithImageName:@"good_coupon_bg"];

        }else{

            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];

            btn.frame=CGRectMake(100,100,100,100);

            [btnsetImage:[UIImage imageWithContentsOfFile:filePath] forState:UIControlStateNormal];

            [self.viewaddSubview:btn];

        }

    }

    /**

     *  删除旧图片

     */

    - (void)deleteOldImage {

        NSString *imageName = [[NSUserDefaults standardUserDefaults] valueForKey:@"sds"];

        if(imageName) {

            NSString*filePath = [selfgetFilePathWithImageName:imageName];

            NSFileManager *fileManager = [NSFileManager defaultManager];

            [fileManagerremoveItemAtPath:filePatherror:nil];

        }

    }

    /**

     *  判断文件是否存在

     */

    - (BOOL)isFileExistWithFilePath:(NSString*)filePath {

        NSFileManager *fileManager = [NSFileManager defaultManager];

        BOOLisDirectory =FALSE;

        return[fileManagerfileExistsAtPath:filePathisDirectory:&isDirectory];

    }

    /**

     *  根据图片名拼接文件路径

     */

    - (NSString*)getFilePathWithImageName:(NSString*)imageName {

        if(imageName) {

            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);

            NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:imageName];

            returnfilePath;

        }

        return nil;

    }

    /**

     *  下载新图片

     */

    - (void)downloadAdImageWithImageName:(NSString*)imageName {

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

        NSString*filePath = [selfgetFilePathWithImageName:imageName];// 保存文件的名称

        if ([UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES]) {// 保存成功

            NSLog(@"保存成功");

            [self deleteOldImage];

            [[NSUserDefaults standardUserDefaults] setValue:imageName ?:@""  forKey:@"sds"];

            [[NSUserDefaults standardUserDefaults] synchronize];

        }else{

            NSLog(@"保存失败");

        }

    }

    解释:- (NSString*)getFilePathWithImageName:(NSString*)imageName 这个方法只是要把将要保存的图片保存到这个方法设置的路径下。(但是此时在沙盒里面,(这里是沙盒里面的Cache)是看不到这个路径的,因为图片还没有成功保存到本地,所以不会在Cache下产生我们设置的文件路径)

    直到[UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES]返回YES,也就是图片成功保存到我们设置好的路径下(文件下),我们才会在Cache下看到我们设置的路径,(也就是图片保存的路径)

    我们通过[NSUserDefaults standardUserDefaults]保存的值,是存在Library ->Preferences下面(以plist文件形式保存)

    文件夹应该就是目录吧

    /**

     *  创建文件夹/目录(返回创建结果)

     */

    -(BOOL)createDir:(NSString*)fileName{

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

      //  NSString *documentsDirectory = [paths objectAtIndex:0];

    //    NSString * path = [NSString stringWithFormat:@"%@/%@",documentsDirectory,fileName];

        NSString* path =  [[pathsobjectAtIndex:0] stringByAppendingPathComponent:fileName];

        NSFileManager *fileManager = [NSFileManager defaultManager];

        BOOLisDir;

        if  (![fileManagerfileExistsAtPath:pathisDirectory:&isDir]) {//先判断目录是否存在,不存在才创建

            BOOL res=[fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];

            returnres;

        }else return NO;

    }

    * NSString *documentsDirectory = [paths objectAtIndex:0];

       NSString * path = [NSString stringWithFormat:@"%@/%@",documentsDirectory,fileName];

    上面这两句代码跟这行代码是一样的 

    NSString* path =  [[pathsobjectAtIndex:0] stringByAppendingPathComponent:fileName];

    /**

     *  创建文件(返回创建结果)

     */

    -(BOOL)createFile:(NSString*)path{

         NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

        NSFileManager *fileManager = [NSFileManager defaultManager];

        NSString *testPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"test"];//在传入的路径下创建test.c文件

        BOOL res = [fileManagercreateFileAtPath:testPathcontents:nilattributes:nil];

        //通过data创建数据

      //  [fileManager createFileAtPath:testPath contents:NULL attributes:nil];

        returnres;

    }

    /**

     *  读文件数据

     */

    -(void)readFile:(NSString*)path{

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

        NSString *testPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"test"];

        //方法1:

    //    NSData * data = [NSData dataWithContentsOfFile:path];

    //    NSString * content = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

        //方法2:

        NSString * content = [NSString stringWithContentsOfFile:testPath encoding:NSUTF8StringEncoding error:nil];

        NSLog(@"文件读取成功: %@",content);

    }

    /**

     *  根据路径删除文件(返回删除结果)

     */

    -(BOOL)deleteFileByPath:(NSString*)path{

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

        NSString *testPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"test"];

        NSFileManager *fileManager = [NSFileManager defaultManager];

        BOOLres=[fileManagerremoveItemAtPath:testPatherror:nil];

        NSLog(@"文件是否存在: %@",[fileManagerisExecutableFileAtPath:path]?@"YES":@"NO");

         returnres;

    }

    // 真机下的路径

    /var/mobile/Containers/Data/Application/976A0BCC-76C2-4AE9-9865-53CDC0860597

    相关文章

      网友评论

          本文标题:iOS -- 本地存储图片和沙盒机制

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