loop to set UIImages from document directory on viewDidLoad - ios

I have 9 buttons whose images are set by the user dynamically. Each button's current image is saved the user documents folder. In viewDidLoad id like to re-set each image to it's UIButton.
I can do this easily enough with:
NSString *filePath = [self documentsPathForFileName: #"boss1.png"];
NSData *pngData = [NSData dataWithContentsOfFile:filePath];
UIImage *savedBoss = [UIImage imageWithData:pngData];
[boss1Button setImage:savedBoss forState:UIControlStateNormal];
...... 8 more times....
Of course Id prefer to do it using a loop. Only, Im not sure what that would look like in objective C. In jQuery I could do something like:
$('.bosses').each(function( index ) {
var imageUrl='../images/boss'+(index+1)
$('#'+this.id).css('background-image', 'url(' + imageUrl + ')')
});
How can I create a similar objective-C loop that would increment the boss image name and button name similarly?
Furthermore, is there a better way to do this entirely?
I feel like maybe having an NSArray of image urls and an NSArray of UIButton names and pairing them together using a loop might be better.... but again I'm not sure what the syntax would look like for that here.

Try like this and have button tag like 1 to 8
for (id subview in self.view.subviews) {
if([subview isKindOfClass:[UIButton class]]) {
UIButton* button = (UIButton*)subview;
NSString *filePath = [self documentsPathForFileName:[NSString stringWithFromate#"boss%d.png", button.tag]];
NSData *pngData = [NSData dataWithContentsOfFile:filePath];
UIImage *savedBoss = [UIImage imageWithData:pngData];
[button setImage:savedBoss forState:UIControlStateNormal];
}
}
This will do.

it will be like:
//Add all the buttons in an array for easy loop
NSArray *array = #[btn1,btn2,btn3,btn4... etc];
NSString *name = #"BOSS";
int x = 1;
for(UIButton *btn in array){ // loop through all the buttons
NSString *filePath = [self documentsPathForFileName:[NSString stringWithFormat:#"%#%d.png",name,x]];
NSData *pngData = [NSData dataWithContentsOfFile:filePath];
UIImage *savedBoss = [UIImage imageWithData:pngData];
[btn setImage:savedBoss forState:UIControlStateNormal];
x++;
}

Related

How to display external image to textview?

I have the following code to display internal image in textview. I am trying to display external http:// link to textview.
The following code works ok. Please help me to display external weblink image.
UITextField *txtstate =[[UITextField alloc]init]; [txtstate setFrame:CGRectMake(10, 30,170, 30)];
txtstate.delegate=self;
NSString * quotStr03 = [[NSString alloc] initWithFormat:#"%#",[dict valueForKey:#"deal-image"]];
txtstate.text=quotStr03;
txtstate.borderStyle = UITextBorderStyleLine;
txtstate.background = [UIImage imageNamed:quotStr03];
[txtstate setAutocorrectionType:UITextAutocorrectionTypeNo];
[self.view addSubview:txtstate];
-(UIImage *) getImageFromURL:(NSURL*) imageURL
{
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
return image;
}
by providing url to this function you will get external weblink image

Receiveing array of Images from CoreData

I've created NSManagedObject* imagesArrayData that stores strings (paths) to images stored in the documents directory:
- (void)setImagesArray:(NSMutableArray *)imagesArray {
NSMutableArray* newImagesArray = [NSMutableArray new];
int i = 1;
for (UIImage* image in imagesArray) {
//generate path to createdFile
NSString* fileName = [NSString stringWithFormat:#"%#_%d", self.name, i];
NSString* filePath = [self documentsPathForFileName:fileName];
//save image to disk
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:filePath atomically:YES];
//add image path to CoreData
[newImagesArray addObject:filePath];
i++;
}
//set new value of imagesArray
imagesArrayData = [NSKeyedArchiver archivedDataWithRootObject:newImagesArray];
I am now not showing pathsToImages in header file, but property imagesArray:
-(NSMutableArray*) imagesArray {
NSMutableArray* images = [NSMutableArray new];
NSArray* imagePaths = [NSKeyedUnarchiver unarchiveObjectWithData:imagesArrayData];
for (NSString* imagePath in imagePaths) {
UIImage *image = [[UIImage alloc] initWithContentsOfFile: imagePath];
[images addObject:image];
}
return images;
The problem is, that whenever I want to get to [imagesArray objectatIndex:xxx], the imagesArray getter is called, and it takes time to recreate the full array. When trying to switch fast between images, the UI slows down.
What would be the elegant way to overcome this problem? Maybe creating another array full of images and updating it from time to time? Maybe something else? Please, help.
One thing you could do is refactor your getter to lazily load the array. If it is already defined, simply return it. If not, build it:
-(NSMutableArray*) imagesArray
{
if (!_imagesArray)
{
NSMutableArray* _imagesArray = [NSMutableArray new];
NSArray* imagePaths =
[NSKeyedUnarchiver unarchiveObjectWithData: imagesArrayData];
for (NSString* imagePath in imagePaths)
{
UIImage *image = [[UIImage alloc] initWithContentsOfFile: imagePath];
[_imagesArray addObject:image];
}
return _imagesArray;
}
I'm not sure what you mean about updating an array of images from time to time.
If your array of image names changes you will need some method to respond to those changes.

Iterating an NSMutableDictionary with UIImage not working

I am trying to add Images fetched from an external service to an NSMutableDictionary and seeing weird results. This is what I am doing:
- (void)fetchImages{
//Fetch Item Brand Images
//self.itemBrands is an NSArray of NSDictionaries
for (NSDictionary *itemBrand in self.itemBrands){
NSString *currentItemId = [itemBrand objectForKey:#"ITEM_ID"];
//Valid Item Id. This Log message is displayed
NSLog(#"Current Item Id: %#",currentItemId);
NSString *currentItemImageUrl = [[IMAGE_URL stringByAppendingString:currentItemId] stringByAppendingString:#".png"];
//Image URL is valid. This log message is displayed
NSLog(#"Current Image URL: %#",currentItemImageUrl);
NSURL *url = [NSURL URLWithString:currentItemImageUrl];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
if (image == nil){
//This log message is displayed when image is not present
NSLog(#"Image not Present 1");
}else{
//This log message is displayed when image is present
NSLog(#"Image Present 1");
[self.itemBrandImages setObject:image forKey:currentItemId];
}
}
//This for loop is not being executed at all. No log messages displayed.
for(id key in self.itemBrandImages){
NSLog(#"Current Item Id2: %#",key);
if ([self.itemBrandImages objectForKey:key] == nil){
NSLog(#"Image Not Present 2");
}else{
NSLog(#"Image Present 2");
}
}
}
The 2nd for loop where I am iterating over self.itemBrandImages is not being executed at all. None of the log messages inside are being displayed.
I tried the following before posting my issue here:
1) Researched similar problems in stack overflow and incorporated suggestion from one of them. The suggestion was "Perform an alloc init of the NSMUtableDictionary" in the init method of the .m file. This didn't help either.
2) To isolate the issue, I even tried adding a simple string to the NSMUtableDictionary instead of the image but even that does not seem to retained.
I am really confused as as to what I am missing or doing wrong here. Inputs are really appreciated.
Thanks,
Mike G
Perhaps:
for(NSString *key in [self.itemBrandImages allKeys])
I did an alloc init of the NSMutableDictianary right in my fetchImages method and it worked! Not sure why the alloc init in the init method did not work.
So here are my takeaways from this issue:
1) If you have an Array or dictionary #property that you are just getting and setting and not really adding or deleting objects to, then you don't need to explicitly alloc init them.
2) If you have an Array or dictionary #property that you are adding or deleting objects to ,you need to explicitly alloc init them.
Are my above statements true? Would love to hear your inputs on this.
Thanks,
Mike
New code:
- (void)fetchImages{
//Fetch Item Brand Images
self.itemBrandImages = [[NSMutableDictionary alloc] init];
for (NSDictionary *itemBrand in self.itemBrands){
NSString *currentItemId = [itemBrand objectForKey:#"ITEM_ID"];
NSLog(#"Current Item Id in ItemList: %#",currentItemId);
NSString *currentItemImageUrl = [[#"http://anythingtogo.freeiz.com/images/"stringByAppendingString:currentItemId] stringByAppendingString:#".png"];
NSLog(#"Current Image URL in ItemList: %#",currentItemImageUrl);
NSURL *url = [NSURL URLWithString:currentItemImageUrl];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
if (image == nil){
NSLog(#"Image not Present 1");
}else{
NSLog(#"Image Present 1");
[self.itemBrandImages setObject:#"Test" forKey:currentItemId];
}
}

How to get file extension (compare)

i´m parsing the filedirectory from dropbox into a mutablearray, to show it in a table view.
how can i compare the file extension? (.doc, or .jpg,....)
if ([[NSString stringWithFormat:#"%#",[test objectAtIndex:indexPath.row]] isEqualToString:#"??????"] ) {
[cell.extensionView setImage:[UIImage imageNamed:#"word.png"]];
}
isEqualToWhat? is it possible to use wildcards?
Don't use stringWithFormat unless you actually have a format. Your code would be much cleaner if you did something like this:
NSString *filename = [text objectAtIndex:indexPath.row];
NSString *ext = [filename pathExtension];
if ([ext isEqualToString:#"doc"]) {
[cell.extensionView setImage:[UIImage imageNamed:#"word.png"]];
} else if ([ext isEqualToString:#".jpg"]) {
[cell.extensionView setImage:[UIImage imageNamed:#"jpeg.png"]];
}
There is a better way than setting up this big if-else block. I imagine you have lots of different extensions you wish to check. Setup a dictionary with the extensions and images. Something like:
NSDictionary *extensionThumbnails = #{
#"doc" : [UIImage imageNamed:#"word.png"],
#"xls" : [UIImage imageNamed:#"excel.png"],
#"jpg" : [UIImage imageNamed:#"jpeg.png"]
};
Add an entry for each extension and image you have. Then your original code (now using modern Objective-C syntax) becomes:
NSString *filename = text[indexPath.row];
NSString *ext = [filename pathExtension];
UIImage *thumbnail = extensionThumbnails[ext];
if (!thumbnail) {
thumbnail = [UIImage imageNamed:#"unknown.png"];
}
[cell.extensionView setImage:thumbnail];

How to separate images out from Resources in iOS

I'm displaying a set of images in my app. I've got the code working when I load the image from the Resources folder, like so:
- (void)viewDidLoad
{
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:[NSString stringWithFormat: #"pic_a"]];
[array addObject:[NSString stringWithFormat: #"pic_b"]];
[array addObject:[NSString stringWithFormat: #"pic_c"]];
[array addObject:[NSString stringWithFormat: #"pic_d"]];
int index = arc4random() % [array count];
NSString *pictureName = [array objectAtIndex:index];
NSString* imagePath = [ [ NSBundle mainBundle] pathForResource:pictureName ofType:#"png"];
UIImage *img = [ UIImage imageWithContentsOfFile: imagePath];
if (img != nil) { // Image was loaded successfully.
[imageView setImage:img];
[imageView setUserInteractionEnabled:NO];
[img release]; // Release the image now that we have a UIImageView that contains it.
}
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
However, if I create an "images" group within the "Resources" group, and put try to load the images from there, the image within the view shows up blank.
[array addObject:[NSString stringWithFormat: #"images/pic_a"]];
[array addObject:[NSString stringWithFormat: #"images/pic_b"]];
[array addObject:[NSString stringWithFormat: #"images/pic_c"]];
[array addObject:[NSString stringWithFormat: #"images/pic_d"]];
I'd like to separate the images out from the nib files and all the other cruft. What's the best way to do that?
Even if you have the images in a separate group within Resources, you can load them by calling the name, e.g. use this one line
UIImage *img = [UIImage imageNamed:[array objectAtIndex:index]];
in place of these three lines:
NSString *pictureName = [array objectAtIndex:index];
NSString* imagePath = [ [ NSBundle mainBundle] pathForResource:pictureName ofType:#"png"];
UIImage *img = [ UIImage imageWithContentsOfFile: imagePath];
You will still fill the array simply by
[array addObject:[NSString stringWithFormat: #"pic_a"]];
If you have both jpg and png files, then you should append .png to the end of the file names. Otherwise, leaving it off is fine.
Try using the imageNamed: method instead of imageWithContentsOfFile:
You need to create a physical folder called images (it should have a blue color instead of the usual yellow color)
Remember that adding groups inside your project it is simply for organization and look within Xcode. You adding a group will not change the fact that the images will be saved in the main bundle. If you are trying to find them using the images group in the string it will not find them.
There are some things you can do to make this work, but in reality you don't need to.

Resources