Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete image from app directory in iPhone

I want to delete an image from my iPhone app. I use the method below, passing the name of the image as an argument.

The problem is that the image isn't deleted.

- (void)removeImage:(NSString*)fileName {

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:
                      [NSString stringWithFormat:@"%@.png", fileName]];

    [fileManager removeItemAtPath: fullPath error:NULL];
    NSLog(@"image removed: %@", fullPath);

    NSString *appFolderPath = [[NSBundle mainBundle] resourcePath];    
    NSLog(@"Directory Contents:\n%@", [fileManager directoryContentsAtPath: appFolderPath]);
}

The last two lines show the content in my app directory and the image I want to delete is still there. What am I doing wrong?

like image 314
bruno Avatar asked Feb 23 '12 14:02

bruno


2 Answers

You are trying to delete a file in the Documents directory. You then read the contents of the bundle resources directory. These are not the same directory.

If you're trying to delete a file in the Documents directory, the you should rad that directory in your NSLog() at the end. If you're trying to delete a file inside your bundle, this is impossible. App bundles are signed and cannot be modified.

like image 140
Rob Napier Avatar answered Sep 20 '22 05:09

Rob Napier


your code looks ok, so try adding some 'NSError' object to you code:

- (void)removeImage:(NSString*)fileName {

   NSFileManager *fileManager = [NSFileManager defaultManager];
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,   YES);
   NSString *documentsDirectory = [paths objectAtIndex:0];
   NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:
                      [NSString stringWithFormat:@"%@.png", fileName]];

   NSError *error = nil;
   if(![fileManager removeItemAtPath: fullPath error:&error]) {
      NSLog(@"Delete failed:%@", error);
   } else {
      NSLog(@"image removed: %@", fullPath);
   }

   NSString *appFolderPath = [[NSBundle mainBundle] resourcePath];    
   NSLog(@"Directory Contents:\n%@", [fileManager directoryContentsAtPath: appFolderPath]);
}

In the code above I passed a NSError the error parameter of removeItemAtPath. If the system can't delete the file, this method will return NO and fill the error object with the error raised.

like image 29
rckoenes Avatar answered Sep 22 '22 05:09

rckoenes