删除app文档目录中的图像

时间:2017-04-18 07:30:04

标签: ios objective-c

我的app文档目录中的“PhotoAlbum”文件夹中有24张图片。如何删除“PhotoAlbum”中的所选图像?如何传递对象索引?

我有这样的事情:

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index
    {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/PhotoAlbum"];

    NSString *fullPath = [dataPath stringByAppendingPathComponent:[self.photos objectAtIndex:index]];
    NSData *pngData = [NSData dataWithContentsOfFile:fullPath];
    UIImage *image = [UIImage imageWithData:pngData];

    MWPhoto *photo = [[MWPhoto alloc] initWithImage:image];
    return photo;
}

2 个答案:

答案 0 :(得分:0)

您无法通过指定索引来删除它。您必须指定要删除的图像名称。它会是这样的

NSString *filePath = [NSString stringWithFormat:@"%@/%@",documentPath,image.imageName];

    NSError *error = nil;
    if ([[NSFileManager defaultManager] fileExistsAtPath:documentPath]){
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
}

答案 1 :(得分:0)

这将删除您的图像并返回已删除的图像。

 - (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index
    {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/PhotoAlbum"];

    NSString *fullPath = [dataPath stringByAppendingPathComponent:[self.photos objectAtIndex:index]];
    NSData *pngData = [NSData dataWithContentsOfFile:fullPath];
    UIImage *image = [UIImage imageWithData:pngData];

    MWPhoto *photo = [[MWPhoto alloc] initWithImage:image];
    if ([[NSFileManager defaultManager] fileExistsAtPath:fullPath]){
            [[NSFileManager defaultManager] removeItemAtPath:fullPath error:&error];
    }

    return photo;
}