Im currently searching my documents folder for .png images using
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:nil];
fileList=[[NSMutableArray alloc]init];
for (NSString *filename in dirContents) {
NSString *fileExt = [filename pathExtension];
if ([fileExt isEqualToString:#"png"]) {
[fileList addObject:filename];
}
}
NSLog(#"document folder content list %# ",fileList);
Id like to make the search more specific, ie search for images named lorry.png, or car.png for example (for brevity) rathe rthan getting everything with .png
My image files are named by apending a reference number self.certificate.reference to the png so I get something like car283TYZ.png. This way I can utilise the correct image for the certificate that created it.
What ive tried
//search folder
NSString *certRefstring = [NSString stringWithFormat:#"%#",self.certificate.reference];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:nil];
fileList=[[NSMutableArray alloc]init];
for (NSString *filename in dirContents) {
NSString *fileExt = [filename pathExtension];
if ([fileExt isEqualToString:#"png"]&&[certRefstring rangeOfString:[NSString stringWithFormat:#"%#",self.certificate.reference]].location == NSNotFound) {
NSLog(#"string does not contain cert ref %#, file list is %#",self.certificate.reference,fileList);
}
else{
NSLog(#"string contains cert ref %# and png files %#",self.certificate.reference,fileList);
[fileList addObject:filename];
}
}
NSLog(#"document folder content list %# ",fileList);
This seemed to return everything in the folder. So im looking for a solution for searching more specifically/iterating over my .png files in my documents folder
NSString *certRefstring = [NSString stringWithFormat:#"%#",self.certificate.reference];
so
[certRefstring rangeOfString:[NSString stringWithFormat:#"%#",self.certificate.reference]].location == NSNotFound
is always NO. There is a reason why you receive everything.
Probably it should be changed to
[filename rangeOfString:[NSString stringWithFormat:#"%#",self.certificate.reference]].location == NSNotFound
You should have nested 'if's
if ([fileExt isEqualToString:#"png"])
{
if ([certRefstring rangeOfString:[NSString stringWithFormat:#"%#",self.certificate.reference]].location == NSNotFound)
{
NSLog(#"string does not contain cert ref %#, file list is %#",self.certificate.reference,fileList);
}
else
{
NSLog(#"string contains cert ref %# and png files %#",self.certificate.reference,fileList);
[fileList addObject:filename];
}
}
Related
I'm getting a problem to find a file from project. I am getting this file using code but I can't get it using url.
Please help me out from this problem.
Here is the path of file
Users/yatish/Library/Developer/CoreSimulator/Devices/65048208-DC46-4B30-9526-470D6D8081D3/data/Containers/Data/Application/2E7EFDA0-9C0C-4440-962D-610C2AC18DDD/Documents/file.txt
Here is the code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *Path = [NSString stringWithFormat:#"%#/%#%#",documentsDirectory,#"file"#".txt"];
[str writeToFile:Path atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSString *fn=#"file";
NSString *searchFilename =[fn stringByAppendingString:#".txt"]; // name of the PDF you are searching for
NSArray *pathss = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectorys = [pathss objectAtIndex:0];
NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:documentsDirectorys];
NSString *documentsSubpath;
BOOL fileFound = false;
while (documentsSubpath = [direnum nextObject])
{
if (![documentsSubpath.lastPathComponent isEqual:searchFilename]) {
continue;
fileFound=NO;
}
NSLog(#"found %#", documentsSubpath);
fileFound =YES;
}
if(fileFound){
NSLog(#"File Found");///this line is execute when i run this code
}
In code, you can use:
NSURL *fileURL = [NSURL URLWithPath: documentsSubpath];
And that will be the path to your file.
If you want to see the actual file, go to the Macintosh Finder and click "Go To Folder" (it's under the "Go" menu, or ⇧⌘G all together). Then type in your path MINUS the last path component, which is the filename. In your case, that is "/Users/yatish/Library/Developer/CoreSimulator/Devices/65048208-DC46-4B30-9526-470D6D8081D3/data/Containers/Data/Application/2E7EFDA0-9C0C-4440-962D-610C2AC18DDD/Documents".
I have the following code, I don't want to get into why I am doing it this way, but for some reason this is not working. The stringURL is working fine, it gets data back, but fails to write to the document directory. This is the first time I'm working with files, and have been pulling my hair out trying to get this to work. Please could someone point me in the right direction?
+ (void) downloadAndStorePDFFromURLWithString: (NSString *) stringURL andFileID: (NSString *) fileID andTitle: (NSString *) title;
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *pdfData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: stringURL]];
dispatch_async(dispatch_get_main_queue(), ^(void) {
//STORE THE DATA LOCALLY AS A PDF FILE
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
documentsDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat: #"%#/%#", fileID, title]];
//GET LOCAL FILE PATH OF DOWNLOADED PDF
//NSLog(#"SUCCESSFULLY DOWNLOADED DOCUMENT FOR FILE: %# WILL BE STORED AT %#", fileID, documentsDirectory);
BOOL success = [pdfData writeToFile: documentsDirectory atomically: YES];
NSLog(success ? #"Yes" : #"No");
//TELL TABLEVIEW TO RELOAD
//[[NSNotificationCenter defaultCenter] postNotificationName: #"DocumentDownloaded" object: nil];
//SAVE FILEPATH URL IN NSUSERDEFAULTS
//[PDFDownloadManager addURLToListOfSavedPDFs: [PDFDownloadManager filePath: fileID andTitle: title] andFileID: fileID];
});
});
}
You are attempting to write the file to a subfolder of the Documents folder. This is failing because the subfolder doesn't exist. You need to create the folder before you can write to it.
You should also clean up the code a bit. And use the better NSData method to write the file.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *folder = [documentsDirectory stringByAppendingPathComponent:fileID];
[[NSFileManager defaultManager] createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:nil error:nil];
NSString *filePath = [folder stringByAppendingPathComponent:title];
NSError *error = nil;
BOOL success = [pdfData writeToFile:filePath options: NSDataWritingAtomic error:&error];
if (!success) {
NSLog(#"Error writing file to %#: %#", filePath, error);
}
How can I retrieve all the images from NSDocumentsDirectory? I don't know the image name but I need to store all the images in NSMutableArray.
Try this dude
-(NSMutableArray*)pullOutAllImagesInDocumentsDirectory{
NSArray *listOfPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [listOfPaths objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
NSMutableArray *imageFilePathsCollection = [[NSMutableArray alloc] init];
for (int imageIndex=0; imageIndex<filePathsArray.count; imageIndex++) {
NSString *strFilePath = [filePathsArray objectAtIndex:0];
if ([[strFilePath pathExtension] isEqualToString:#"png"]||
[[strFilePath pathExtension] isEqualToString:#"PNG"]||
[[strFilePath pathExtension] isEqualToString:#"jpg"]) {
[imageFilePathsCollection addObject:[filePathsArray objectAtIndex:imageIndex]];
}
}
return imageFilePathsCollection;
}
NOTE: it will give image url path. in order to get the image, you can use
[yourImageView setImage:[UIImage imageWithContentsOfFile:"Path Of Image"]];
I assuming you mean the Documents Directory specific to your app sandbox. If so you can access that directory using [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
Cycle through that directory and look for files that have a .png or .jpg e.t.c. path extension.
i.e:
NSString *string = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSArray *array = [[NSFileManager defaultManager] contentsAtPath:string];
for (NSString *doc in array) {
NSLog(#"%#", doc);
if ([doc.pathExtension isEqualToString:#"jpg"]) {
// Is jpg image obviously you want to search for different formats also
}
}
Im trying to read contents of a specific folder in documents directory thats contains only png's /Documents/ApplianceImagesFolder/
Currently I can only get all my images from documents folder, how can I target contents of ApplianceImagesFolder only?
//gets all png form documents folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:nil];
fileList=[[NSMutableArray alloc]init];
for (NSString *dir in dirContents) {
if ([dir hasSuffix:#".png"]) {
NSRange range = [dir rangeOfString:#"."];
NSString *name = [dir substringToIndex:range.location];
if (![name isEqualToString:#""]) {
[fileList addObject:name];
}
}
}
NSLog(#"document folder content list %# ",fileList);
Build the desired path:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *folderPath = [documentsPath stringByAppendingPathComponent:#"ApplianceImagesFolder"];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:nil];
And there's a better way to find the png files:
fileList=[[NSMutableArray alloc]init];
for (NSString *filename in dirContents) {
NSString *fileExt = [filename pathExtension];
if ([fileExt isEqualToString:#"png"]) {
[fileList addObject:filename];
}
}
NSLog(#"document folder content list %# ",fileList);
In my app I download a pdf file with an ASiHttpRequest and I have these instructions:
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[currentDownload setDownloadDestinationPath:[documentsDirectory stringByAppendingPathComponent:#"file.pdf"]];
it work fine at first time, and I can open this file.pdf, but when I download a second time this pdf, it seems that it not replace the file but do a merge.
before I do this, but it doesn't work where is the problem, or what's the best way to delete this file.pdf from its path?
- (void) removeFile{
NSString *extension = #"pdf";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPDF = [paths objectAtIndex:0];
NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectoryPDF error:NULL];
NSEnumerator *e = [contents objectEnumerator];
NSString *filename;
while ((filename = [e nextObject])) {
if ([[filename pathExtension] isEqualToString:extension]) {
[fileManager removeItemAtPath:[documentsDirectoryPDF stringByAppendingPathComponent:filename] error:NULL];
}
}
}
EDIT
now I use this method
- (void) removeFile{
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0]stringByAppendingString:#"/file.pdf"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSLog(#"Documents directory before: %#", [fileManager contentsOfDirectoryAtPath:[paths objectAtIndex:0] error:&error]);
if([fileManager fileExistsAtPath:path] == YES)
{
NSLog(#"file exist and I delete it");
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:path error:&error];
NSLog(#"error:%#", error);
}
NSLog(#"Documents directory after: %#", [fileManager contentsOfDirectoryAtPath:[paths objectAtIndex:0] error:&error]);
}
this method recognize that in directory there is "file.pdf" in NSLog
NSLog(#"Documents directory before: %#", [fileManager contentsOfDirectoryAtPath:[paths objectAtIndex:0] error:&error]);
but it crash after
"NSLog(#"file exist and I delete it");"
and I have only a "lldb" in consolle.
I use this method to delete pdf files from a local cache, with a few modifications you can adapt it to your necessities
- (void)removePDFFiles
{
NSFileManager *fileMngr = [NSFileManager defaultManager];
NSArray *cacheFiles = [fileMngr contentsOfDirectoryAtPath:[self cacheDirectory]
error:nil];
for (NSString *filename in cacheFiles) {
if ([[[filename pathExtension] lowercaseString] isEqualToString:#"pdf"]) {
[fileMngr removeItemAtPath:[NSString stringWithFormat:#"%#/%#", [self cacheDirectory], filename] error:nil];
}
}
}
Most probably you don't remove the file before downloading a new one and ASIHttpRequest sees that there's already a file with the same name and appends data to it instead of replacing the file. I'm not sure about the PDF format, but that shouldn't normally result in a merged readable file. In any case, first you need to use the error mechanism that the filemanager class offers you. Is bad to pass NULL. Very bad. So, create a NSError object and pass it to the contentsOfDirectoryAtPath and removeItemAtPath methods, then check the error, be sure the operations are done successfully. After that, you may want to check the extension upper case as well, as Unix based systems are case sensitive (although the simulator is not, the device is) and a example.PDF file will not get deleted based on your code.
Try the following:
-(BOOL) removePDF
{
BOOL removeStatus = NO;
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString* fileName = #"file.pdf"; //your file here..
NSString* filePath = [NSString stringWithFormat:#"%#/%#", docsDir, fileName];
if([[NSFileManager defaultManager] fileExistsAtPath:filePath] == YES)
{
removeStatus = [[NSFileManager defaultManager] removeItemAtPath:filePath];
}
return removeStatus;
}