In my application I Use NSFileManager to get the number of files in a folder using following code
NSFileManager *manager=[NSFileManager defaultManager];
NSString *path;
int numberofFiles=[[manager contentsOfDirectoryAtPath:path error:nil] count];
numberofFiles=numberofFiles-1; //number of files except .DS_Store
But my problem is that the file .DS_Store is not always created defaultly, at that time I get less count than the count of files actually present in that directory .
So is there a method in NSFileManager which return the array of files excluding .DS_Store
or I have to exclude manually using -IsEqualToString method
or else is there any option to create a new directory without .DS_Store file.
Explicitly look for the .DS_Store file and adjust the count if it's found:
NSFileManager *manager=[NSFileManager defaultManager];
NSString *path = ...; // Presumably this is a valid path?
NSArray *contents = [manager contentsOfDirectoryAtPath:path error:nil];
NSUInteger numberOfFiles = [contents count];
if ([contents indexOfObject:#".DS_Store"] != NSNotFound)
numberOfFiles--;
Try this.. Its working for me..
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *imageFilenames = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];
for (int i = 0; i < [imageFilenames count]; i++)
{
NSString *imageName = [NSString stringWithFormat:#"%#/%#",documentsDirectory,[imageFilenames objectAtIndex:i] ];
if (![[imageFilenames objectAtIndex:i]isEqualToString:#".DS_Store"])
{
UIImage *myimage = [UIImage imageWithContentsOfFile:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:_myimage];
}
}
Related
I want make a zip file containing multiple documents, documents are taken from my Document Directory.
BOOL isDir=NO;
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray *subpaths;
for(int i=0; i<[arrdocument count]; i++)
{
NSString *toCompress = [arrdocument objectAtIndex:i];
NSString *pathToCompress = [documentsDirectory stringByAppendingPathComponent:toCompress];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:pathToCompress isDirectory:&isDir] && isDir){
subpaths = [fileManager subpathsAtPath:pathToCompress];
} else if ([fileManager fileExistsAtPath:pathToCompress]) {
subpaths = [NSArray arrayWithObject:pathToCompress];
}
NSString *zipFilePath = [documentsDirectory stringByAppendingPathComponent:#"myZipFileName2.zip"];
ZipArchive *za = [[ZipArchive alloc] init];
[za CreateZipFile2:zipFilePath];
if (isDir) {
for(NSString *path in subpaths){
NSString *fullPath = [pathToCompress stringByAppendingPathComponent:path];
if([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && !isDir){
[za addFileToZip:fullPath newname:path];
}
}
} else {
[za addFileToZip:pathToCompress newname:toCompress];
}
}
But when I look at the zip file it shows only one document inside the zip file?
It seems like you recreate the zip file in each loop iteration. You should instead move the creation of the zip file out of the loop or just specify appending when you create the zip file like this:
[za CreateZipFile2:zipFilePath append:YES];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *zipFile = [documentsDirectory stringByAppendingPathComponent:#"compressed.zip"];
ZipArchive *zip = [[ZipArchive alloc] init];
BOOL result = [zip CreateZipFile2:zipFile];
if(result){
NSError *error;
NSArray *allFiles = arrdocument;
for(int index = 0; index<allFiles.count; index++){
id singleFileName = [allFiles objectAtIndex:index];
NSString *singleFilePath = [documentsDirectory stringByAppendingPathComponent:singleFileName];
[zip addFileToZip:singleFilePath newname:singleFileName];
}
[zip CloseZipFile2];
}else{
[self showErrorMessage:#"Unable to to create zip file. Please try again later" withTitle:#"Error"];
}
My Application creates Png, Pdf, and Jpg files and stores in Documentary with different name formats. How can i retrieve all filetypes at a time. For example If i want to count how many number of pdf files in documentary, where all files exists and i have to count only pdf files. How can i achieve this for particular file types.
NSFileManager *filemanage = [NSFileManager defaultManager];
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSArray *filelist= [filemanage contentsOfDirectoryAtPath:[docPaths objectAtIndex:0] error:nil];
NSInteger filescount = [filelist count];
NSString *filesnumber = [NSString stringWithFormat:#"%d", filescount];
NSLog(#"filesnumber:%#", filesnumber);
fileLabel.text = filesnumber;
NSFileManager *filemanage = [NSFileManager defaultManager];
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSArray *filelist= [filemanage contentsOfDirectoryAtPath:[docPaths objectAtIndex:0] error:nil];
NSInteger filescount = 0;
for (NSString *fileName in filelist) {
if ([[fileName pathExtension] isEqualToString:#"pdf"]) {
filescount++;
}
}
NSString *filesnumber = [NSString stringWithFormat:#"%d", filescount];
NSLog(#"filesnumber:%#", filesnumber);
fileLabel.text = filesnumber;
You could || the if statement to add .jpg, .png and whatever else you may want.
NSFileManager *filemanage = [NSFileManager defaultManager];
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSArray *filelist = [filemanage contentsOfDirectoryAtPath:[docPaths objectAtIndex:0] error:nil];
NSInteger fileCountPDF = 0;
for (NSString *fileName in filelist) {
NSString *extension = fileName.pathExtension;
if ([extension caseInsensitiveCompare:#"pdf"] == NSOrderedSame) {
NSLog(#"PDF file found");
fileCountPDF++;
}
}
NSLog(#"PDF files: %d",fileCountPDF);
//...
I am saving an image however it is just duplicating itself since I only set only one name however I want it to count up so that it wont replace itself. Is there any way to do this?
NSArray *directoryNames = [NSArray arrayWithObjects:#"hats",#"bottoms",#"right",#"left",nil];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
for (int i = 0; i < [directoryNames count] ; i++) {
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:[directoryNames objectAtIndex:i]];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil]; //Create folder
NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:#"hats"]; // "right" is at index 2, per comments & code
NSString *filePath = [folderPath stringByAppendingPathComponent:#"hats.PNG"]; // you maybe want to incorporate a timestamp into the name to avoid duplicates
NSData *imageData = UIImagePNGRepresentation(captureImage.image);
[imageData writeToFile:filePath atomically:YES];
}
Use timestamp value as filename to avoid duplicates
I am using writeToFile:atomically: to update the value of a key in my plist by 1 every time the app is launched. I put this code in viewDidLoad, which reads the string value of the key, gets the numeric value of that string, increases it by 1, converts it back to a string, and writes that as the new string for that key, but when I read it again it seems to have not updated. I can't figure out what I'm doing wrong. I don't need a special framework for writeToFile:atomically:, do I?
Here is the code:
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"DaysLaunched.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path])
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"DaysLaunched" ofType:#"plist"];
[fileManager copyItemAtPath:bundle toPath:path error:&error];
}
NSMutableDictionary *plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
NSMutableDictionary *data1 = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
NSString *currentNumberOfDays = [NSString stringWithFormat:#"%#",[plistDict objectForKey:#"numberOfDays"]];
NSLog(#"currentNumberOfDays = %#", currentNumberOfDays); //0
int days = [currentNumberOfDays intValue];
days ++;
currentNumberOfDays = [NSString stringWithFormat:#"%d", days];
[data1 setObject:[NSString stringWithFormat:#"numberOfDays"] forKey:currentNumberOfDays];
NSLog(#"currentNumberOfDays = %#", currentNumberOfDays); //1
[data1 writeToFile: path atomically:YES];
currentNumberOfDays = [NSString stringWithFormat:#"%#",[plistDict objectForKey:#"numberOfDays"]];
NSLog(#"currentNumberOfDays = %#", currentNumberOfDays); //0 ??????? writeToFile isn't working?
And here is a screenshot of "DaysLaunched.plist" in my 'Supporting Files' folder, (I've also verified that the plist file name is spelled exactly the same way I spelled it in my code, via Copy-Paste)
The original plist file is also in my 'Copy Bundle Resources' in targets.
Try
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"DaysLaunched.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path])
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"DaysLaunched"
ofType:#"plist"];
[fileManager copyItemAtPath:bundle toPath:path error:&error];
}
NSMutableDictionary *plistDict = [NSMutableDictionary dictionaryWithContentsOfFile:path];
NSInteger days = [plistDict[#"numberOfDays"] integerValue];
plistDict[#"numberOfDays"] = [#(++days) stringValue];
[plistDict writeToFile: path atomically:YES];
You have made a mistake while setting your data.
You should do:
[data1 setObject:currentNumberOfDays forKey:#"numberOfDays"];
instead of:
[data1 setObject:[NSString stringWithFormat:#"numberOfDays"] forKey:currentNumberOfDays];
I have a .plist file which have this structure,
I want to add or replace the Item 5. I am using this code
NSError *error ;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"Introduction.plist"];
NSMutableArray *data = [[NSMutableArray alloc] initWithContentsOfFile:path];
NSString *comment = str;
[data replaceObjectAtIndex:1 withObject:comment];
[data writeToFile:path atomically:YES];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:path]) {
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"Introduction" ofType:#"plist"];
[fileManager copyItemAtPath:bundle toPath:path error:&error];
}
If I change replaceObjectAtIndex: to 5 it changes my plist structure, and I don't want that.
How can I insert/replace the text at the row 5 (Item 5) of particular Index?
You structure has an array of arrays.
[data replaceObjectAtIndex:1 withObject:comment];
By this code you are replacing an array at index 1 with a string. Do you specifically need to insert to 5th index or do you just need to add it to existing sub array?
NSMutableArray *subArray = [data[sectionIndex] mutableCopy];
if (!subArray) {
subArray = [NSMutableArray array];
}
if (rowIndex<[subArray count]) {
[subArray replaceObjectAtIndex:rowIndex withObject:comment];
}else{
[subArray addObject:comment];
}
[data replaceObjectAtIndex:sectionIndex withObject:subArray];
[data writeToFile:path atomically:NO];
Access the subArray, make it mutable and add or insert at specific index. If you are trying to insert don't forget to include a check if the index is not greater than count of that array.