How to get List of Images Using NSBundle - iphone

I am having List of images in my project i have to get the entire list Using NSBundle, How can i do this
Thank You

This should do it:
NSLog(#"Images in bundle are:");
NSString *imageExtension = #"png";
NSArray *pngPaths = [[NSBundle mainBundle] pathsForResourcesOfType:imageExtension inDirectory:nil];
for (NSString *filePath in pngPaths)
{
NSString *fileName = [filePath lastPathComponent];
NSLog(#"%#", fileName);
}
Just change the imageExtension string for the image type you want.

Related

Reading from text file - Objective C

I am trying to familiarize myself with objective C, and my current goal is to read a list of items in a text file and store them in a NSString array.
Currently this is what I have:
NSString *filepath = [[NSBundle mainBundle] pathForResource:#"myList" ofType:#"txt"];
NSData* data = [NSData dataWithContentsOfFile:filepath];
NSString* string = [[NSString alloc] initWithBytes:[data bytes]
length:[data length]
encoding:NSUTF8StringEncoding];
NSString* delimiter = #"\n";
listArray = [string componentsSeparatedByString:delimiter];
I am not sure if this matters, but myList.txt is in my Supporting Files.
At the moment, I only have one item in my list. However I am unable to store even that 1 item into my listArray.
I am sure it is something silly that I am missing, I am just new to Objective C.
EDIT:
I apologize for not mentioning this earlier. I AM NOT receiving any sort of error. My array is just null.
I'm going to suggest a little simplification which might solve your problem since I can't say what your problem is. From the information I'm not sure if you are getting the proper file contents when reading it in or not.
NSString *filepath = [[NSBundle mainBundle] pathForResource:#"myList" ofType:#"txt"];
NSError *error;
NSString *fileContents = [NSString stringWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:&error];
if (error)
NSLog(#"Error reading file: %#", error.localizedDescription);
// maybe for debugging...
NSLog(#"contents: %#", fileContents);
NSArray *listArray = [fileContents componentsSeparatedByString:#"\n"];
NSLog(#"items = %d", [listArray count]);
If the content of the file is just like:
[{"Title":"20","Cost":"20","Desc":""},{"Title":"10","Cost":"10.00","Desc":""},{"Title":"5","Cost":"5.00","Desc":""}]
try this
-(id)readFromDocumentDBFolderPath:(NSString *)fileName
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
NSFileManager *fileManager=[NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:appFile])
{
NSError *error= NULL;
NSData* data = [NSData dataWithContentsOfFile:appFile];
id resultData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
if (error == NULL)
{
return resultData;
}
}
return NULL;
}

Save arrays in folders

I want to create different folders for each user's account. There are images of user's that are need to be stored in their folder. How can i achieve that i am getting no idea.Can anyone help me.
Thanks in advance.
Create directory in your app like this:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:#"UniqueUserAccount"];
if (![[NSFileManager defaultManager] fileExistsAtPath:folderPath])
[[NSFileManager defaultManager] createDirectoryAtPath:folderPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
Now saving NSMutableArray refer read-and-write-array-dictionary-and-other-collections-to-files link.
folderPath = [folderPath stringByAppendingPathComponent:#"array.out"];
[yourArray writeToFile:folderPath atomically:YES];
Read array like this:
NSArray *arrayFromFile = [NSArray arrayWithContentsOfFile:folderPath];
NSLog(#"%#",arrayFromFile);
EDIT : To save image in user account folder from array of images
for(int i = 0;i < [arrImages count];i++)
{
folderPath = [folderPath stringByAppendingPathComponent:[NSString stringWithFormat:#"Images%d",i]]; //here folder Path with Image file
//Our goal is to create UIImage into NSData if u have image in bundle then take like this:
NSMutableString *imgPath;
imgPath=[[NSMutableString alloc] initWithString: [[NSBundle mainBundle] resourcePath]]; //get bundle path
[imgPath stringByAppendingPathComponent:[arrImages objectAtIndex:i]]; //get image from bundle to write
NSData *imageData = [NSData dataWithContentsOfFile:imgPath]; //create nsdata of image
//if u have UIImage
NSData *imageData = UIImagePNGRepresentation([arrImages objectAtIndex:i]) //image reference here to convert into data
[imageData writeToFile:folderPath atomically:YES]; //write here
}
you can create directory in your app by:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *newFolder = [(NSString*)[paths objectAtIndex:0] stringByAppendingPathComponent:#"uniqueIdentifierForAccount"];
if (![[NSFileManager defaultManager] fileExistsAtPath:newFolder]) {
[[NSFileManager defaultManager] createDirectoryAtPath:newFolder withIntermediateDirectories:YES attributes:nil error:nil];
}
It sounds to me that rather than needing actual folders, you really just need to store an array connected to a name. I would advise using the NSUserDefaults. You can achieve this functionality like this:
//instantiate the NSUserDefaults
NSUserDefaults *storage = [NSUserDefaults standardUserDefaults];
NSArray *userArray;
NSString *username;
//Then to store:
[storage setObject:userArray forKey:username];
//and to recall:
userArray = [storage objectForKey:username];

NSURL, creating pdfs

I'm trying to create some pdfs from pdfs added to my iphone as an exercise for myself in quartz and just getting better with the language. So I have this so far to get the multiple pdfs on my phone:
NSError *error;
NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:bundleRoot error:&error];
NSArray *onlyPDFs = [dirContents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"self ENDSWITH '.pdf'"]];
How can I convert this to a NSURL object, or an array of NSURL objects? I've tried some different things like URLForResource, initWithString, but I don't think those are correct. Thanks.
You could do something like this to generate an NSURL for each PDF in onlyPDFs:
for (NSString *p in onlyPDFs) {
NSString *name = [p stringByDeletingPathExtension];
NSURL *url = [[NSBundle mainBundle] URLForResource:name withExtension:#"pdf"];
}

how to get multiple types of file using pathsForResourcesOfType

I need to access all jpg,png,bmp in my Resources folder, but
doing the following only gives me jpg...
is it algorithmically wrong?
or is there a shorter, simpler syntax that makes me access all three at once?
Please help me out..
NSMutableArray *paths = [[[NSBundle mainBundle] pathsForResourcesOfType:#"jpg" inDirectory:nil] mutableCopy];
NSMutableArray *paths2 = [[[NSBundle mainBundle] pathsForResourcesOfType:#"png" inDirectory:nil] mutableCopy];
NSMutableArray *paths3 = [[[NSBundle mainBundle] pathsForResourcesOfType:#"bmp" inDirectory:nil] mutableCopy];
for(NSString *filename in paths)
{
filename = [filename lastPathComponent];
NSLog(#" filename is %#", filename);
[filenames addObject:filename];
NSLog(#" filenames array length is now %d", [filenames count]);
}
and so on for paths2 and paths3...
The problem with #Ole Begemann's solution is that you will be reiterating through a lot of files that aren't images. I think #CosmicRabbitMediaInc was on the right track with the mutable array, but didn't follow through. So:
NSMutableArray *paths = [NSMutableArray arrayWithArray:[[NSBundle mainBundle] pathsForResourcesOfType:#"jpg" inDirectory:nil]];
[paths addObjectsFromArray:[[NSBundle mainBundle] pathsForResourcesOfType:#"png" inDirectory:nil]];
[paths addObjectsFromArray:[[NSBundle mainBundle] pathsForResourcesOfType:#"bmp" inDirectory:nil]];
for(NSString *filename in paths)
{
filename = [filename lastPathComponent];
NSLog(#" filename is %#", filename);
[filenames addObject:filename];
NSLog(#" filenames array length is now %d", [filenames count]);
}
You can specify nil for the extension to retrieve all bundle resources. Then, in the for loop, check for [filename pathExtension].

grabbing data from an internal file

I'm grabbing data from an external file using NSURL with the code below. If i wanted to grab this data from an internal file in my resources folder how would the code be different.
here's the NSURL code:
NSURL *dataUrl = [NSURL URLWithString:#"https://sites.google.com/site/*****/***/file.asc"];
NSString *fileString = [NSString stringWithContentsOfURL:dataUrl encoding:NSUTF8StringEncoding error:nil];
this was my attempt:
NSString *path = [[NSBundle mainBundle] pathForResource:#"fileName" ofType:#"asc"];
NSString *fileString = [NSString initWithContentsOfFile:path];
thanks in advance
Maybe try stringByExpandingTildeInPath
something like
NSString *path = [[NSBundle mainBundle] pathForResource:#"fileName" ofType:#"asc"];
path = [path stringByExpandingTildeInPath];
NSString *fileString = [NSString initWithContentsOfFile:path];