天天看点

IOS 沙盒存取图片

-(BOOL)setPhotoToPath:(UIImage *)image isName:(NSString *)name

{

    //获取沙盒路径

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

    //并给文件起个文件名,并组合路径

    pathStr = [[paths objectAtIndex:0] stringByAppendingPathComponent:name];

    //判断是否存在当前文件

    result = [[NSFileManager defaultManager] fileExistsAtPath:pathStr];

    if (result)

    {

       //如果存在,调用删除方法,返回NO

        [self deletePhotoToPath:pathStr];

        return NO;

    }

    else

    {

        NSData * data = UIImagePNGRepresentation(BGimage);

        BOOL writeResult = [data writeToFile:pathStr atomically:YES];

        if (writeResult)

        {

            NSLog(@"write to path succeed");

            return YES;

        }

        else

        {

            NSLog(@"write to path failure");

            return NO;

        }

    }

}

-(UIImage*)getPhotoToPath:(NSString *)name

{

    //获取沙盒路径

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

    //并给文件起个文件名,并组合路径

    pathStr = [[paths objectAtIndex:0] stringByAppendingPathComponent:name];

    //判断是否存在当前文件

    result = [[NSFileManager defaultManager] fileExistsAtPath:pathStr];

    if (result)

    {

        NSData * data = [NSData dataWithContentsOfFile:pathStr];

        BGimage = [UIImage imageWithData:data];

        return BGimage;

    }

    else

    {

        NSLog(@"don't find file");

        return nil;

    }

}

//存储图片

-(BOOL)deletePhotoToPath:(NSString *)name

{

   //获取沙盒路径

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

    //并给文件起个文件名,并组合路径

    pathStr = [[paths objectAtIndex:0] stringByAppendingPathComponent:name];

    //判断是否存在当前文件

    result = [[NSFileManager defaultManager] fileExistsAtPath:pathStr];

    NSFileManager * fileManager = [NSFileManager defaultManager];

    if (result)

    {

       BOOL DeleteResult = [fileManager removeItemAtPath:pathStr error:nil];

        if (DeleteResult)

        {

            return YES;

            NSLog(@"delete succeed");

        }

        else

        {

            NSLog(@"delete Failure");

            return NO;

        }

    }

    else

    {

        NSLog(@"don't find file");

        return NO;

    }

}