How to get image URL out of NSArray? - iphone

So I have an NSDictionary with 4 objects in it. Each of these objects then has 2 properties, name and date
I can list out all the data by logging it.

You have an NSArray which contains several dictionaries. Firstly,get one dictionary out of the array like this,
NSDictionary *myDict=[myArray objectAtIndex:0];
assuming u have this array under the name myArray. You will get the first dictionary from the array which contains medium,thumbnails,title and another key called url. thumbnails is an array which holds a dict wid a key called url. Now if u want to fetch the outside url key tat is in the myArray just do like this,
NSString *myURL=[myDict valueForKey:#"url"];
This should fetch the url value..Hope this helps.... Happy coding...
NSData *myData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:myURL]];
UIImage *myImage = [[UIImage alloc] initWithData:myData;
Now you have ur image. Just create an imageView and set this image to it. To add it to a table, use contentView property like this,
[cell.contentView addSubView:myImageView];
Hope this helps.

Related

Check if exists a string inside a plist file

Hello guys i try to check a single line STRING inside my plist file, in my detail view I need to implement a IF like a:
NSString *data = [[NSBundle mainBundle] pathForResource:#"name" ofType:#"plist"];
NSMutableDictionary *dataDict = [[NSMutableDictionary alloc] initWithContentsOfFile:data];
self.myMutableDictionary = dataDict;
if (name.text == [myMutableDictionary objectForKey:#"emittente"]){
UIImage *image = [UIImage imageNamed:#"star_on.png"];
[Star setImage:image];
} else {
UIImage *favImg = [UIImage imageNamed:#"star_Off.png"];
[Star setImage:favImg];
}
But dosent work, i think no reading inside the plist file, any idea or metod for do that?
Thanks.
Actually, your code looks almost fine. Just check the following:
Does your plist contain the key #"emittente" on the top level? If not, you have to descend down your dictionaries or arrays to get to the right level.
Also, you are comparing pointers in your if statement, not strings. Use this instead:
if ([name.text isEqualToString:myMutableDictionary[#"emittente"]) ...
BTW: you should not use uppercase instance variable names.

Pictures put into a array Ios developing

I have a folder with pictures in my project and i like to know how i could put this pictures from the folder into a array
How should i do that?
I tried this to put the images in the array
UIImage*image = [[NSBundle mainBundle]pathsForResourcesOfType:#"jpg" #"jpeg" #"gif" inDirectory:#"Images"];
NSArray*images = [[NSMutableArray alloc]initWithContentsOfFile:image];
You could do the following, getting the array of filenames and then filling another array with the images, themselves (assuming that's what you were trying to do).
NSMutableArray *imagePaths = [[NSMutableArray alloc] init];
NSMutableArray *images = [[NSMutableArray alloc] init];
NSArray *imageTypes = [NSArray arrayWithObjects:#"jpg", #"jpeg", #"gif", nil];
// load the imagePaths array
for (NSString *imageType in imageTypes)
{
NSArray *imagesOfParticularType = [[NSBundle mainBundle]pathsForResourcesOfType:imageType
inDirectory:#"Images"];
if (imagesOfParticularType)
[imagePaths addObjectsFromArray:imagesOfParticularType];
}
// load the images array
for (NSString *imagePath in imagePaths)
[images addObject:[UIImage imageWithContentsOfFile:imagePath]];
As an aside, unless these are tiny thumbnail images and you have very few, it generally would not be advisable to load all the images at once like this. Generally, because images can take up a lot of RAM, you would keep the array of filenames, but defer the loading of the images until you really need them.
If you don't successfully retrieve your images, there are two questions:
Are the files included in my bundle? When you select the "Build Phases" for your Target's settings and expand the "Copy Bundle Resources" (see the image below), do you see your images included? If you don't see your images in this list, they won't be included in the app when you build it. To add your images, click on the "+" and add them to this list.
Are the files in a "group" or in an actual subdirectory? When you add files to a project, you'll see the following dialog:
If you chose "Create folder references for added folders", then the folder will appear in blue in your project (see the blue icon next to my "db_images" folder in the preceding screen snapshot). If you chose "create groups for added folders", though, there will be the typical yellow icon next to your "Images" group. Bottom line, in this scenario, where you're looking for images in the subdirectory "Images", you want to use the "Create folder references for added folders" option with the resulting blue icon next to the images.
Bottom line, you need to ensure the images are in your app bundle and that they are where you think they are. Also note that iOS is case sensitive (though the simulator is not), so make sure you got the capitalization of "Images" right.
If I am understanding your question correctly initWithContentsOfFile doesn't do what you are expecting, per the documentation:
"Initializes a newly allocated array with the contents of the file specified by a given path."
Additionally, pathsForResourceOfType is already creating an array, not a UIImage, you can simply do:
NSArray* images = [[NSBundle mainBundle]pathsForResourcesOfType:#"jpg" #"jpeg" #"gif" inDirectory:#"Images"];
[[NSBundle mainBundle]pathsForResourcesOfType:#"jpg" #"jpeg" #"gif" inDirectory:#"Images"];
already returns an array of these objects. Change your line to this:
NSArray *images = [[NSBundle mainBundle]pathsForResourcesOfType:#"jpg" #"jpeg" #"gif" inDirectory:#"Images"];
Note that this array will only hold the paths for all your images. In order to make images of them you need to call
for(NSString* imagePath in images) {
UIImage* anImage = [[UIImage alloc] initWithContentsOfFile:imagePath];
//do something with your image here.
}
Hope that helps
Read the documentation of initWithContentsOfFile method of NSArray:
The array representation in the file identified by aPath must contain only property list objects (NSString, NSData, NSArray, or NSDictionary objects). The objects contained by this array are immutable, even if the array is mutable.
In your case you need to use NSFileManager to enumerate files in directory. Here is the example of directory enumeration from documentation:
NSFileManager *localFileManager=[[NSFileManager alloc] init];
NSDirectoryEnumerator *dirEnum =
[localFileManager enumeratorAtPath:docsDir];
NSString *file;
while (file = [dirEnum nextObject]) {
if ([[file pathExtension] isEqualToString: #"doc"]) {
// Create an image object here and add it to
// mutable array
}
}
[localFileManager release];
Try this:
NSMutableArray* paths=[NSMutableArray new];
NSFileManager* manager=[NSFileManager new];
NSBundle* bundle= [NSBundle mainBundle];
NSDirectoryEnumerator* enumerator= [manager enumeratorAtPath: [bundle bundlePath] ];
for(NSString* path in enumerator)
{
if([path hasSuffix: #".jpg"] || [path hasSuffix: #".jpeg"] || [path hasSuffix: #".gif"])
{
[paths addObject: path];
}
}
For explanations I suggest that you look at NSDirectoryEnumerator documentation.

iPhone:Convert NSMutableArray to NSData with stored & retrieved issue

I am facing a problem, that is to convert NSMutableArray into NSData and stored & retrieved that array into rootviewcontroller so please give me idea. Here is the code I'm working with:
appDelegate = (FindNearMeAppDelegate *)[[UIApplication sharedApplication]delegate];
appDelegate.isCategoryCell = TRUE;
appDelegate.isButton = NO;
NSString *categoryStr = categoryName.text;
NSLog(#"Category Name:--->%#",categoryStr);
appDelegate.categoryData = [NSMutableDictionary dictionaryWithObjectsAndKeys:
categoryStr, #"name",image ,#"image", nil];
[appDelegate.categories addObject:appDelegate.categoryData];
NSLog(#"Category Data:--->%#",appDelegate.categories);
I am initialize nsmutablearray (appDelegate.categories) and nsmutabledictionary in appdelegate.
Thanks in advance.
From what I understand, you want to save your images and retrieve them. You can convert your image to NSData using one of the 2 methods, UIImagePNGRepresentation or UIImageJPEGRepresentation depending on the type of the image. You can then save this data-
NSData* imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:imagePath atomically:YES]; //imagePath is where you want to save it. Most likely it contains the value of the name key in your dictionary.

how to fetch image from array and show it on table view

I am fetching image from server and save it on a NSMutableArray. The result of array like that
myarray={"roger_50.jpg",....};
Now i dont know how to access this image on table view.
Just have proper URL for image in array. And pass it to NSURL object as a link.
NSURL *imageURL = [NSURL URLWithString:[myarray objectAtIndex : yourindex]];
NSData *data = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [[UIImage alloc] initWithData:data];
Have a nice coding.
Stay Hungry, Stay Foolish...
i hope the thing you are getting from array are only the names you can retrieve images from server in only two ways i) in nsdata ii)by url of the images on sever .By this way you cann't access the images.

Need help creating .plist in app

My app ships with a .plist that looks like this:
I want the user to be able to add a custom exerciseName.
So I need to create a new .plist in the user's document folder that mimics this format. Can anyone help me with this?
I need something like this (pseudo code)
if (userData == nil)
{
then create the .plist file;
setup the .plist to mimic the format of the img above.
}
now save exerciseName appropriately.
Update:
if (exerciseArray == nil)
{
NSString *path = [[NSBundle mainBundle]pathForResource:#"data" ofType:#"plist"];
NSMutableArray *rootLevel = [[NSMutableArray alloc]initWithContentsOfFile:path];
self.exerciseArray = rootLevel;
[rootLevel release];
}
What you will want to do is load the Plist into an NSDictionary, and encode that NSDictionary back to a Plist file in your applications document folder. In your applicationDidFinishLoading: method, I would do something like this:
NSString * documentFile = [NSHomeDirectory() stringByAppendingFormat:#"/Documents/myPlist.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:documentFile]) {
// create a copy of our resource
NSString * resPath = [[NSBundle mainBundle] pathForResource:#"myPlist" ofType:#"plist"];
// NOTE: replace #"myPlist" with the name of the file in your Resources folder.
NSDictionary * dictionary = [[NSDictionary alloc] initWithContentsOfFile:resPath];
[dictionary writeToFile:documentFile atomically:YES];
[dictionary release];
}
Then, when you want to add an item, you want to use an NSMutableDictionary to modify and save the existing plist in the app's documents directory:
- (void)addExercise {
NSMutableDictionary * changeMe = [[NSMutableDictionary alloc] initWithContentsOfFile:documentFile];
... make changes ...
[changeMe writeToFile:documentFile atomically:YES];
[changeMe release];
}
To make changes, you will need to find the sub-dictionary containing the array of exercises. Then use the setObject:forKey: method on the NSMutableDictionary to set a new array containing a new list of exercises. This might look something like this:
NSMutableArray * list = [NSMutableArray arrayWithArray:[changeMe objectForKey:#"list"]];
NSArray * exercises = [[list objectAtIndex:10] objectForKey:#"exercises"];
NSDictionary * newExercise = [NSDictionary dictionaryWithObject:#"Type a LOT" forKey:#"exerciseName"];
exercises = [exercises arrayByAddingObject:newExercise];
NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithDictionary:[list objectAtIndex:10]];
[dict setObject:exercises forKey:#"exercises"];
[list replaceObjectAtIndex:10 withObject:dict];
[changeMe setObject:list forKey:#"list"];
Once you make your change, it is important to remember to write changeMe to the plist file in the documents directory.
The easiest way to read and write property lists is to use the NSArray or NSDictionary classes. Your screenshot appears to be an array at the top level, so I will use that assumption for my examples.
First you need paths to the user file and original file.
NSString *pathToUserFile; // Get a path to the file in the documents directory
NSString *pathToDefaultFile; // Get a path to the original file in the application bundle
You then attempt to load the
NSMutableArray *userData;
NSArray *temporary = [NSArray arrayWithContentsOfFile:pathToUserFile];
if(!temporary) temporary = [NSArray arrayWithContentsOfFile:pathToDefaultFile];
Since it appears that you are using multiple layers containers, I am assuming that you will need the innermost arrays and dictionaries to be mutable. The normal initialization of NSMutableArray will not do this, so you need to use CFPropertyListCreateDeepCopy with the options set to have mutable containers.
userData = (NSMutableArray *)CFPropertyListCreateDeepCopy(NULL,(CFArrayRef)temporary,kCFPropertyListMutableContainers);
You now have a mutable object representing your data. You can add objects or modify existing objects the same way you handle any array, but you can only add strings, numbers, data objects, dictionaries, arrays, and dates, since those are the only types valid in property lists.
[userData addObject:newDataObject];
Finally, you write the data out to the file in the documents directory. The writeToFile:atomically: method will attempt to write out a property list, and return YES if successful. It will fail and return NO if the file could not be written, or if the contents are not all valid property list objects.
if(![userData writeToFile:pathToUserFile atomically:YES]) {
NSLog(#"Error writing to file");
}