How to get path for images objective-C - objective-c

I want to call images from different folder, would you please help me to implement this;
I have this structure for my folders :
Folder1
file1
image1.jpg
file2
image2.jpg
file3
image3.jpg
Folder2 ....
inside of each file%d I have one image%.jpg
I want to call my images in loop,
for (i = 1; i > image; i++)
{
NSString *image = [NSString stringWithFormat:#"image%d.jpg", i];
But my question is how to enter to the folders and get images
can I have something like this :
stringWithFormat:#"Folder%d/File%d/image%d" ofType:#"jpg"
what is the best way?
Thanks in advance!

Here are a few useful code snippets that work for me.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *mapDirPath = [documentsDirectory stringByAppendingPathComponent:#"/MapCache"];
// Creating a directory in the documents directory
NSError* error;
if (![[NSFileManager defaultManager] fileExistsAtPath:mapDirPath])
[[NSFileManager defaultManager] createDirectoryAtPath:mapDirPath withIntermediateDirectories:NO attributes:nil error:&error];
// loading an image
NSString *filePath = [self.localImagePath stringByAppendingPathComponent: key];
if ( [[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
UIImage* image = [UIImage imageWithContentsOfFile:filePath];
return image;
}
// Writing an image
[[NSFileManager defaultManager] createFileAtPath:filePath contents:remoteData attributes:nil];
Hope that helps
Of course, if you're reading images from your bundle, you want this instead
[[NSBundle mainBundle] pathForResource: #"filename" ofType:#"png" directory: #"directory1"]

Right, this is how I would do it.
for (f = 1; f <= numberOfFolders; i++) {
for (i = 1; i <= numberOfImages; i++) {
NSString* file = [NSString stringWithFormat: #".../Folder%d/File%d/image%d.jpg", f, i, i];
NSImage* image = [NSImage imageNamed: file];
// Do something with the image
}
}
A note: I don't know where Folder1/Folder2... etc are, so I used '.../' on the code. Be sure to fill that part appropriately.

Iterate folders and images appending the image path to the library path:
NSString * libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
for (NSUInteger f = 1; f <= numFolders; i++) {
for (NSUInteger i = 1; i <= numImages; i++) {
// Create the image path
NSString * imagePath = [NSString stringWithFormat:#"%#/Folder%d/File%d/image%d.jpg", libraryPath, f, i, i];
// Check if file exists
if ( [[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
UIImage * image = [UIImage imageWithContentsOfFile:imagePath];
// Use image...
}
else {
NSLog(#"Image not found.");
}
}
}

Related

writeToFile does not work after removeItemAtPath

I have an iOS app that at times needs to store UIImage objects locally.
I am using [UIImagePNGRepresentation(image) writeToFile:full_path options:NSAtomicWrite error:nil]; to save the image and [file_manager removeItemAtPath:full_path error:NULL]; to delete the file.
This all works great, however, whenever I delete a file, should I decide to save a new file (which just so happens to have the same name as the old file), the save code doesn't work and returns the following error:
: ImageIO: CGImageReadCreateDataWithMappedFile 'open' failed
error = 2 (No such file or directory)
: ImageIO: CGImageReadCreateDataWithMappedFile 'open' failed
error = 2 (No such file or directory)
: ImageIO: PNG zlib error
So heres what I don't get, why can't I save a file with the same name as the old file, after I have deleted the old file?
The reason I ask this, is that, my app will save certain image files and then when they are no longer needed, my app will delete them. However, there are times when my app needs the image files again (could be a few hours after deletion or a few weeks). When this happens, my app will load the appropriate image data and then try to save it. And thats when the error occurs.
Whats going wrong here?
Thanks for your time, Dan.
UPDATE - Here are the methods I have setup to save/access and delete my image files
-(void)save_local_image:(UIImage *)image :(NSString *)file_name {
// Get the app documents directory link.
NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
// Add the new file name to the link.
NSString *database_link = [[NSString alloc] initWithString:[documents stringByAppendingPathComponent:file_name]];
// Save the image data locally.
[UIImagePNGRepresentation(image) writeToFile:database_link options:NSAtomicWrite error:nil];
}
-(UIImage *)get_local_image:(NSString *)file_name {
// Create the return data.
UIImage *image_data = nil;
// Get the app documents directory.
NSArray *directory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] error:NULL];
// Only check for data if at least
// one file has been saved locally.
if ([directory count] > 0) {
// Loop through the different local files.
for (NSString *path in directory) {
// Get the full local file URL.
NSString *full_path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:path];
// Get the range of the file name.
NSRange range = [full_path rangeOfString:file_name];
// Get the image data if it exists.
if ((range.location != NSNotFound) || (range.length == [file_name length])) {
// Load the image file in.
image_data = [UIImage imageWithContentsOfFile:full_path];
break;
}
}
}
return image_data;
}
-(void)delete_local_image:(NSString *)file_name {
// Get the app documents directory.
NSArray *directory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] error:NULL];
// Only check for data if at least
// one file has been saved locally.
if ([directory count] > 0) {
// Loop through the different local files.
for (NSString *path in directory) {
// Get the full local file URL.
NSString *full_path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:path];
// Get the range of the file name.
NSRange range = [full_path rangeOfString:file_name];
// Delete the local image data if it exists.
if ((range.location != NSNotFound) || (range.length == [file_name length])) {
NSError *testError = nil;
// Delete the image file.
NSFileManager *file_manager = [[NSFileManager alloc] init];
BOOL success = [file_manager removeItemAtPath:full_path error:&testError];
NSLog(#"%d", success);
if (testError != nil) {
NSLog(#"%#", testError.localizedDescription);
}
break;
}
}
}
}
I am using this to save and read:
- (void) saveImageToFile:(NSString *) urlImg withNameNumber:(int)numberName andQuestionId:(int) questionID
{
NSString* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString* foofile = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"gallery%d%d.jpg",numberName,questionID]];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];
if (!fileExists) {
NSData *tempImgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",#"https://testurl/",urlImg]]];
NSString *filename = [NSString stringWithFormat:#"gallery%d%d.jpg",numberName,questionID];
NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:filename];
[tempImgData writeToFile:imagePath atomically:YES];
}
}
-(UIImage*) readImageFromFile:(int)numberName andQuestionId:(int) questionID
{
NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
return [UIImage imageWithContentsOfFile:[NSString stringWithFormat:#"%#/gallery%d%d.jpg",documentsDirectoryPath,numberName,questionID]];
}

How to zip folders in Ipad

In my Application,I am taking screenshots of image View and then I am saving those screen shots in document folder of the application.Now I want to Email all those images with the same folder structure they are in.Zipping all the folders containing the images?
-(void)ZipFile2{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [paths objectAtIndex:0];
BOOL isDir=NO;
NSArray *subpaths;
NSString *exportPath = docDirectory;
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:exportPath isDirectory:&isDir] && isDir){
subpaths = [fileManager subpathsAtPath:exportPath];
}
NSString *archivePath = [docDirectory stringByAppendingString:#"Uploads.zip"];
ZipArchive *archiver = [[ZipArchive alloc] init];
[archiver CreateZipFile2:archivePath];
for(NSString *path in subpaths)
{
NSString *longPath = [exportPath stringByAppendingPathComponent:path];
if([fileManager fileExistsAtPath:longPath isDirectory:&isDir] && !isDir)
{
[archiver addFileToZip:longPath newname:path];
}
}
BOOL successCompressing = [archiver CloseZipFile2];
if(successCompressing)
NSLog(#"Success");
else
NSLog(#"Fail");
}
I use this code but the zip file is not created in my Ipad ??? can you Help Me
ZipArchive has a delegate protocol which sends a message whenever a error occurs.
add below ZipArchive allocation.
archiver.delegate = self
Add protocol to header class and then implement the following method:
- (void)ErrorMessage:(NSString*) msg {
NSLog(#"Zip error: %#", msg);
}

NSFileManager fileExistsAtPath:isDirectory issue

Can someone help me understand what I'm doing wrong with this method?
I'm trying to recursively detect the contents of directories and create an xml file in each one. Non-recursive works perfectly and outputs proper xml files. Recursive chokes on dir detection and add's all files + dir's under the "directories" element.
_dirArray = [[NSMutableArray alloc] init];
_fileArray = [[NSMutableArray alloc] init];
NSError *error;
NSFileManager *filemgr = [NSFileManager defaultManager];
NSArray *filelist = [filemgr contentsOfDirectoryAtPath:dirPath error:&error];
for (int i = 0; i < filelist.count; i++)
{
BOOL isDir;
NSString *file = [NSString stringWithFormat:#"%#", [filelist objectAtIndex:i]];
[_pathToDirectoryTextField stringValue], [filelist objectAtIndex:i]];
if ([filemgr fileExistsAtPath:dirPath isDirectory:&isDir] && isDir) // I think this is what is crapping out.
{
[_dirArray addObject:file];
}
else
{
if ([file hasPrefix:#"."])
{
// Ignore file.
}
else
{
[_fileArray addObject:file];
}
}
}
Thanks for any tips guys.
i can see "if ([fileManager fileExistsAtPath:fontPath isDirectory:&isDir] && isDir)" coming from Apple's examples in the documentation but to copy it piecemeal and use it with else is a very bad idea unless you only want to get directories or deleted files because what it means is:
if (itexists and itsadirectory){
//its a existing directory
matches directories
}else{
//it is not a directory or it does not exist
matches files that were deleted since you got the listing
}
here is how i would do it:
NSString *dirPath = #"/Volumes/Storage/";
NSError *error;
NSFileManager *filemgr = [NSFileManager defaultManager];
NSArray *filelist = [filemgr contentsOfDirectoryAtPath:dirPath error:&error];
for (NSString *lastPathComponent in filelist) {
if ([lastPathComponent hasPrefix:#"."]) continue; // Ignore file.
NSString *fullPath = [dirPath stringByAppendingPathComponent:lastPathComponent];
BOOL isDir;
BOOL exists = [filemgr fileExistsAtPath:fullPath isDirectory:&isDir];
if (exists) {
if (isDir) {
[_dirArray addObject:lastPathComponent];
}else{
[_fileArray addObject:lastPathComponent];
}
}
}

iOS list existing directories

I already get path for documents directory and create some directories inside. I already know how to check if directory exist, delete it or its files but, how could I list directories? Thank you.
for file listing I use:
int Count;
NSString *path;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
path = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"SomeDirectoryName"];
NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:NULL];
for (Count = 0; Count < (int)[directoryContent count]; Count++)
{
NSLog(#"File %d: %#", (Count + 1), [directoryContent objectAtIndex:Count]);
}
For example, this method removes all files from temporary directory of application:
- (void)cleatTmpDirectory
{
// Create a local file manager instance
NSFileManager *localFileManager = [[NSFileManager alloc] init];
NSURL *directoryToScan = [NSURL fileURLWithPath:[self applicationTmpDirectory]];
NSDirectoryEnumerator *dirEnumerator =
[[localFileManager enumeratorAtURL:directoryToScan
includingPropertiesForKeys:[NSArray arrayWithObjects:NSURLIsDirectoryKey,nil]
options: NSDirectoryEnumerationSkipsHiddenFiles |
NSDirectoryEnumerationSkipsSubdirectoryDescendants |
NSDirectoryEnumerationSkipsPackageDescendants
errorHandler:nil] retain];
NSError *error;
// Enumerate the dirEnumerator results, each value is stored in allURLs
for (NSURL *theURL in dirEnumerator)
{
// Retrieve whether a directory.
NSNumber *isDirectory;
[theURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:NULL];
if ([isDirectory boolValue] == NO)
{
[localFileManager removeItemAtURL:theURL error:&error];
}
}
// Release the localFileManager.
[localFileManager release];
}
As you can find you should use NSDirectoryEnumerator *dirEnumerator and pass to its initialization method appropriate keys that you will then use.
Use the NSDirectoryEnumerator returned by NSFileManager's -enumeratorAtPath: method.

Appending NSString while using NSApplicationSupportDirectory to create a new directory

I have been trying to create a new file inside of my application support folder while using NSApplicationSupportDirectory; I can write a file to it, but I have been unable to create a folder inside of Application Support.
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *applicationDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the application support: (attempting to create the blasted directory inside of application support directory
NSString *fileName = [NSString stringWithFormat:#"%#/managersemail.txt",
applicationDirectory];
//create content - formats with the managersemail.txt location
NSString* content = [NSString stringWithFormat:#"%#",[nameField stringValue]];
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
NSDictionary* errorDict;
The code that I have listed above works great, except for the part about creating the folder in which I want to place the managersemail.txt. I tried to mimic the stringWithFormat that is listed in the NSString* content and then varying several ways however to no avail! Any thoughts?
NSAppleEventDescriptor* returnDescriptor = NULL;
Perhaps the solution provided on Cocoa with Love might be useful?
Excerpt:
- (NSString *)findOrCreateDirectory:(NSSearchPathDirectory)searchPathDirectory
inDomain:(NSSearchPathDomainMask)domainMask
appendPathComponent:(NSString *)appendComponent
error:(NSError **)errorOut
{
// Search for the path
NSArray* paths = NSSearchPathForDirectoriesInDomains(
searchPathDirectory,
domainMask,
YES);
if ([paths count] == 0)
{
// *** creation and return of error object omitted for space
return nil;
}
// Normally only need the first path
NSString *resolvedPath = [paths objectAtIndex:0];
if (appendComponent)
{
resolvedPath = [resolvedPath
stringByAppendingPathComponent:appendComponent];
}
// Check if the path exists
BOOL exists;
BOOL isDirectory;
exists = [self
fileExistsAtPath:resolvedPath
isDirectory:&isDirectory];
if (!exists || !isDirectory)
{
if (exists)
{
// *** creation and return of error object omitted for space
return nil;
}
// Create the path if it doesn't exist
NSError *error;
BOOL success = [self
createDirectoryAtPath:resolvedPath
withIntermediateDirectories:YES
attributes:nil
error:&error];
if (!success)
{
if (errorOut)
{
*errorOut = error;
}
return nil;
}
}
if (errorOut)
{
*errorOut = nil;
}
return resolvedPath;
}
Maybe you can try using the NSFileManager to create the folder, then write the file into the folder.
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *applicationSupport = [[NSString stringWithString:#"~/Library/Application Support/'YOUR APP'] stringByExpandingTildeInPath];
if ([fileManager fileExistsAtPath:applicationSupport] == NO)
[fileManager createDirectoryAtPath:applicationSupport withIntermediateDirectories:YES attributes:nil error:nil];
NSString *fileName = [NSString stringWithFormat:#"%#/managersemail.txt", applicationSupport];
NSString* content = [NSString stringWithFormat:#"%#",[nameField stringValue]];
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
So something like that should work. Feel free to leave comments to ask questions.