简体   繁体   中英

Delete image in app document directory

I have 24 images in a "PhotoAlbum" folder in my app document directory. How to delete a selected image in the "PhotoAlbum"? How do I pass the object index?

I have something like this:

- (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;
}

You can't delete it by specifying an index. You have to specify the image name you wanted to delete. It will be something like this

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

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

This will delete your image and return deleted image.

 - (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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM