Delete image from application directory on iPhone

I want to remove an image from my iPhone application. I use the method below, passing the image name as an argument.

The problem is that the image is not 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 contents in my application directory, and the image I want to delete still exists. What am I doing wrong?

+6
source share
3 answers

You are trying to delete a file in the Documents folder. Then you read the contents of the package resource directory. This is not the same directory.

If you are trying to delete a file in the Documents folder, you should delight this directory in your NSLog () at the end. If you are trying to delete a file inside your package, this is not possible. Application packages are signed and cannot be changed.

+5
source

your code looks fine, so try adding some "NSError" object to it:

 - (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 above code, I passed NSError the removeItemAtPath error parameter. If the system cannot delete the file, this method will return NO and fill the error object with an error .

+4
source

Based on your comment, I found out that you are trying to remove default.png and replace it with another. Unfortunately this is not possible. The default.png image is part of your application package, which cannot be modified after its creation and signing (this is a safety indicator from Apple, therefore applications cannot change after viewing them). The only places where you can create and delete files are in the sandbox specified by your application (the Documents folder).

+2
source

Source: https://habr.com/ru/post/909189/


All Articles