How can you remove all the files that are saved using the NSFileManager ? I found something like the code below, but you need to give the filePath and since I need to delete all the images that I've saved, I don't know all the image paths/names?
[[NSFileManager defaultManager] removeItemAtPath:filePath error:NULL];
First get all the item from that particular folder :
NSString *filePath = [NSString stringWithFormat:#"your folder path where you have saved those images"];
NSArray *files = [fileManager contentsOfDirectoryAtPath:filePath
error:nil];
this will be the array of the files just loop through the array .and use:
for(NSString *filename in files)
{
NSString *filePath = [NSString stringWithFormat:#"filepath/%#",filename];
[[NSFileManager defaultManager] removeItemAtPath:filePath error:NULL];
}
This should do the trick.
You must be saving your images to any of the folders like, Documents Directory, Library, Caches, or Temp folders. You need to fetch all the images inside any of your directory where you have saved your images using following code..
-(NSArray*)getImagesFromDirectory:(NSString*)imageDirectoryPath{
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSArray *files = [fileManager contentsOfDirectoryAtPath:imageDirectoryPath
error:nil];
return files;
}
Then loop to remove images at path
NSArray *images=[self getImagesFromDirectory:#"DIRECTORYPATH"];
NSFileManager * fileManager = [[NSFileManager alloc] init];
for(NSString *imagePath in images){
[fileManager removeItemAtPath:imagePath];
}
Related
I have unzipped a file and sent to my documents directory:
[SSZipArchive unzipFileAtPath:path toDestination:destinationPath];
In the unzipped file there will be 5 different types of files. I only want to know the path and file name for the file with an extension type of '.shp'.
I've tried the following:
NSString *filePath = [[NSBundle mainBundle] pathForResource:destinationPath ofType:#"shp"];
Afterwards, I would like to delete all the contents of the files in that folder.
Any ideas? Thanks in advance.
First, get all directory files.
NSString *bundle = [[NSBundle mainBundle] bundlePath];
NSFileManager * aMan = [NSFileManager defaultManager];
NSArray * allFiles = [aMan contentsOfDirectoryAtPath: bundle];
Then it is possible to filter needed extension with one of following methods:
NSPredicate *filter = [NSPredicate predicateWithFormat:#"self ENDSWITH '.shp'"];
NSArray *filtered = [allFiles filteredArrayUsingPredicate:filter];
Next - delete files, looping filtered. But it looks not good for me.
So, I prefer this one:
NSError *error;
for (NSString * elem in allFiles) {
if ([[elem pathExtension] isEqualToString:#"shp"])
[aMan removeItemAtPath:[bundle stringByAppendingPathComponent:elem] error:&error];
Hope, it helps
You can use NSFileManager to remove the files:
NSFileManager * fileManager = [[NSFileManager alloc]init];
[fileManager removeItemAtPath:#"your path" error:nil];
You can do it in the following way:
NSURL *baseURL = [NSURL URLWithString:destinationPath];
NSDirectoryEnumerator* filesEnumerator = [[NSFileManager defaultManager] enumeratorAtURL:baseURL includingPropertiesForKeys:#[] options:0 errorHandler:nil];
NSURL* fileURL;
while (fileURL = [filesEnumerator nextObject]) {
NSString* file = [fileURL lastPathComponent];
BOOL match = [file containsString:#".shp"];
if (match) {
[[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil];
}
}
Please let me know if it resolves the problem..
I am trying to upload sqlite file on iCloud. I am using NSFileCoortinator for coping the file from one file to another file but schema of sqlite file is only get copied, I am not getting data in sqlite file….Also sometimes the data is appearing in the sqlite file on iCloud. I don’t understand why this is happening. Is this sqlite file issue or I did wrong in code. If anyone has solution please help me out.
-(void)uploadFile
{
//-------code for uploading data to icloud
NSArray *paths =
NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory,
NSUserDomainMask, YES);
NSString *applicationSupportDirectory = [paths firstObject]
NSString *str=[NSString stringWithFormat:#"%#/XMPPMessageArchiving.sqlite",applicationSupportDirectory]; //copy this file
NSString *fileName = [NSString stringWithFormat:#"XMPPMessageArchiving.sqlite"];
NSURL *ubiq = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
NSURL *fromURL = [NSURL fileURLWithPath:str];
NSURL *toURL = [[ubiq URLByAppendingPathComponent:#"Documents"]
URLByAppendingPathComponent:fileName];;
[coordinator coordinateReadingItemAtURL:fromURL options:0 writingItemAtURL:toURL options:NSFileCoordinatorWritingForReplacing error:nil byAccessor:^(NSURL *newReadingURL, NSURL *newWritingURL)
{
NSError *error=nil;
NSData *data = [[NSFileManager defaultManager] contentsAtPath:fromURL.path];
//if file is already present on icloud replace that file with new file
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:newWritingURL.path];
if (fileExists)
{
[[NSFileManager defaultManager] removeItemAtPath:toURL.path error:NULL];
}
BOOL isCopied= [[NSFileManager defaultManager] copyItemAtPath:newReadingURL.path toPath:newWritingURL.path error:nil];
NSLog(#"file copied= %d",isCopied);
}];
}
The value for file copied is always 1 but still data is not available.
i want to create folder in document directory and want to save images in that folder. i have tried but the folder and the images are storing in document directory..But i want to store the images inside the folder.my code is working fine but the images are not saving inside Folder..
NSError *error;
NSString *aDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *dataPath = [aDocumentsDirectory stringByAppendingPathComponent:#"Folder"];
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
NSInteger anIndex = 0;
for (UIImage *anImage in _chosenImages)
{
NSString *anImageName = [NSString stringWithFormat:#"%d.png", anIndex++];
NSString *anImagePath = [NSString stringWithFormat:#"%#/%#", aDocumentsDirectory, anImageName];
NSLog(#"the path is=%#",anImagePath);
NSData *anImageData = UIImagePNGRepresentation(anImage);
[anImageData writeToFile:anImagePath atomically:YES];
}
I guess your "anImagePath" is still pointing to documents directory.
edit it as "dataPath" as the argument as below
NSString *anImagePath = [NSString stringWithFormat:#"%#/%#", dataPath, anImageName];
try this..
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:&error];
actually you arr passing NO in "withIntermediateDirectories" parameter, and if you pass NO to this than if any of the intermediate parent directories does not exist. This method also fails if any of the intermediate path elements corresponds to a file and not a directory.
I have an app where I have a certain amount of .jpg pictures (roughly 300). They serve as something to start with, because they're actually located in the internet, but obviously it's more convenient for user not to download all of them at the first start of the App, but to have them pre-packed.
I am required to rewrite these images everytime I get new information from server. Obviously, I can't touch the app bundle, so I see my steps like this:
Unpack the images from bundle to the Documents Directory at the first start of an App.
Access them only from Documents Directory, but not from bundle.
If it's necessary, I should rewrite them.
And thus my code will be unified, cause I will always use the same path to get the image.
The problem is that I know very little about the whole file system thing in iOS, so I don't know how to unpack the particular bundle contents to Documents Directory and also I don't know how to write to Documents Directory either.
Could you please help me with some code and also confirm that my solution scheme is right?
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *destPath = [documentsDirectory stringByAppendingPathComponent:#"images"]; //optionally create a subdirectory
//"source" is a physical folder in your app bundle. Once that has a blue color folder (not the yellow group folder)
// To create a physical folder in your app bundle: drag a folder from Mac's Finder to the Xcode project, when prompts
// for "Choose options for adding these files" make certain that "Create folder references for …" is selected.
// Store all your 300 or so images into this physical folder.
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"source"];
NSError *error;
[[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:destPath error:&error];
if (error)
NSLog(#"copying error: %#", error);
Edited per additional comment from the OP:
To rewrite with the same file name to the same directory, you can use a combination of fileExistsAtPath and removeItemAtPath to detect and remove the existing file before writing.
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
[[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
}
// now proceed to write-rewrite
Try this code
-(void)demoImages
{
//-- Main bundle directory
NSString *mainBundle = [[NSBundle mainBundle] resourcePath];
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = [[NSError alloc] init];
NSArray *mainBundleDirectory = [fm contentsOfDirectoryAtPath:mainBundle error:&error];
NSMutableArray *images = [[NSMutableArray alloc]init];
for (NSString *pngFiles in mainBundleDirectory)
{
if ([pngFiles hasSuffix:#".png"])
{
[images addObject:pngFiles];
}
}
NSLog(#"\n\n Doc images %#",images);
//-- Document directory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
//-- Copy files form main bundle to document directory
for (int i=0; i<[images count]; i++)
{
NSString *toPath = [NSString stringWithFormat:#"%#/%#",documentDirectory,[images objectAtIndex:i]];
[fileManager copyItemAtPath:[NSString stringWithFormat:#"%#/%#",mainBundle,[images objectAtIndex:i]] toPath:toPath error:NULL];
NSLog(#"\n Saved %#",fileManager);
}
}
EDIT: Solution at the end of the post
I'm having trouble creating a subdirectory of NSCachesDirectory and adding an NSData object to it. I've referred to multiple SO posts related to this but when I debug my code, it tells me that the NSData file in the folder doesn't exist. My code:
NSURL *photoURL = [FlickrFetcher urlForPhoto:self.singlePhotoDictionary
format:FlickrPhotoFormatLarge];
NSData *URLToData = [NSData dataWithContentsOfURL:photoURL];
NSString *cacheDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *newDirectory = [cacheDirectory stringByAppendingPathComponent:#"Photos"];
BOOL isDir = NO;
NSError *error;
if (! [[NSFileManager defaultManager] fileExistsAtPath:newDirectory isDirectory:&isDir] && isDir == NO)
{
[[NSFileManager defaultManager]createDirectoryAtPath:newDirectory withIntermediateDirectories:NO attributes:nil error:&error];
}
NSString *filePath = [newDirectory stringByAppendingPathComponent:#"thePhotos.jpg"];
NSLog(#"%#", filePath);
//[URLToData writeToFile:filePath atomically:NO];
[[NSFileManager defaultManager] createFileAtPath:filePath contents:URLToData attributes:nil];
NSData *theData = [[NSFileManager defaultManager] contentsAtPath:filePath];
NSArray *contentsInManager = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:newDirectory error:nil];
theData and contentsInManager turn out to be:
theData NSData * 0x00000000
contentsInManager NSArray * 0x00000000
Any help here? The subdirectory exists but the file won't be created inside of it.
As a side question: When do we need to make our own instance of NSFileManager as opposed to using the defaultManager?
Thanks in advance!
SOLUTION: After trial and error, I tried deleting the subdirectory and recreating it. Once I did, the file was able to write to the subdirectory.