Nothing displayed after splitting a list of image URLs - objective-c

I have six image URLs in a string named aux. I split it with component separated by newlines. I want to pick images one by one from aux and display each in an ImageView. My code is:
aux = [_homeText.text stringByAppendingString:[NSString stringWithFormat:#" %# ",item.shortDescription]];
[_homeText setText:aux];
NSString *list =aux;
NSArray *listItems = [list componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
[listItems count];
if ([listItems objectAtIndex:0]) {
NSURL *url = [NSURL URLWithString:aux];
/*UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"hai" message:aux delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert show];
[alert release];*/
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [[UIImage alloc] initWithData:data];
[_homeImage setImage:image];
}
else if ([listItems objectAtIndex:1])
{
NSURL *url = [NSURL URLWithString:aux];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [[UIImage alloc] initWithData:data];
[_homeImage setImage:image];
}
There is no error but I get no image. Why? How do I fix this?

If both data and image not nil, you may try to correctly initialize _homeImage.
I don'w know why, but I think what you created _homeImage like this:
_homeImage = [[UIImageView alloc] init];
Try to do something like this:
CGSize imageSize = [image size];
[_homeImage setFrame:CGRectMake([_homeImage frame].origin.x,
[_homeImage frame].origin.y,
imageSize.width, imageSize.height)];
[_homeImage setImage:image];
[image release], image = nil;

Related

iOS: Issue Saving Photo

I'm very new to Objective-C, and am having some beginner issues. I have an application that has an area that is supposed to behave somewhat like a photo gallery. The user chooses a picture from their camera roll, and the photos get displayed in UIImageViews. I'm trying to save the image that they select. I have 9 UIImageView's, and the issue is that when I select a different photo for each UIImageView, close and relaunch the app, the other 8 UIImageViews display the photo that is stored in the first image view. Here is the code that I'm working with:
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:kFilename9];
}
- (void)applicationDidEnterBackground:(UIApplication*)application {
NSLog(#"Image on didenterbackground: %#", imageView);
self.imageData = [NSData dataWithData:UIImagePNGRepresentation(imageView.image)];
self.imageData = [NSData dataWithData:UIImagePNGRepresentation(imageView2.image)];
self.imageData = [NSData dataWithData:UIImagePNGRepresentation(imageView3.image)];
self.imageData = [NSData dataWithData:UIImagePNGRepresentation(imageView4.image)];
self.imageData = [NSData dataWithData:UIImagePNGRepresentation(imageView5.image)];
self.imageData = [NSData dataWithData:UIImagePNGRepresentation(imageView6.image)];
self.imageData = [NSData dataWithData:UIImagePNGRepresentation(imageView7.image)];
self.imageData = [NSData dataWithData:UIImagePNGRepresentation(imageView8.image)];
self.imageData = [NSData dataWithData:UIImagePNGRepresentation(imageView9.image)];
[self.imageData writeToFile:[self dataFilePath] atomically:YES];
NSLog(#"The image is: %#", [[imageView image] description]);
NSLog(#"dataFilePath is: %#", [self dataFilePath]);
}
- (void)viewDidLoad
{
NSString *filePath = [self dataFilePath];
NSLog(#"FilePath: %#", filePath);
NSLog(#"Image: %#", imageView);
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSData *vdlData = [[NSData alloc] initWithContentsOfFile:filePath];
imageView.image = [[UIImage alloc] initWithData:vdlData];
imageView2.image = [[UIImage alloc] initWithData:vdlData];
imageView3.image = [[UIImage alloc] initWithData:vdlData];
imageView4.image = [[UIImage alloc] initWithData:vdlData];
imageView5.image = [[UIImage alloc] initWithData:vdlData];
imageView6.image = [[UIImage alloc] initWithData:vdlData];
imageView7.image = [[UIImage alloc] initWithData:vdlData];
imageView8.image = [[UIImage alloc] initWithData:vdlData];
imageView9.image = [[UIImage alloc] initWithData:vdlData];
}
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(applicationDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:app];
[super viewDidLoad];
}
I'm trying to figure out what I need to change to get the UIImageViews to display the correct pictures, rather than them all displaying the same picture. This is probably a simple fix, but any help would be greatly appreciated, thanks!
Okay, here's how I would do it:
Use NSUserDefaults to save your images as a mutable array:
ViewController.h
#property(retain) NSUserDefaults *user;
ViewController.m
#synthesize user;
- (void)viewWillAppear:(BOOL)animated
{
self.user = [NSUserDefaults standardUserDefaults];
Edit
NSMutableArray* array = [[self.user objectForKey:#"images"]mutableCopy];
while(array == nil)
{
[self.user setObject:[NSMutableArray arrayWithObject:#""] forKey:#"images"]
array = [[self.user objectForKey:#"images"]mutableCopy];
NSLog(#"%#",#"attempting to create an array to store the images in");
}
End Edit
}
- (void)applicationDidEnterBackground:(UIApplication*)application {
NSLog(#"Image on didenterbackground: %#", imageView);
NSMutableArray* array = [NSMutableArray arrayWithObject:[NSData dataWithData:UIImagePNGRepresentation(imageView.image)]];
[array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView2.image)];
[array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView3.image)];
[array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView4.image)];
[array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView5.image)];
[array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView6.image)];
[array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView7.image)];
[array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView8.image)];
[array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView9.image)];
[self.user setObject:array forKey:#"images"];
}
- (void)viewDidLoad
{
NSMutableArray* array = [[self.user objectForKey:#"images"]mutableCopy];
EDIT
if(array.count == 9)
{
imageView.image = [[UIImage alloc] initWithData:[array objectAtIndex:0]];
imageView2.image = [[UIImage alloc] initWithData:[array objectAtIndex:1]];
imageView3.image = [[UIImage alloc] initWithData:[array objectAtIndex:2]];
imageView4.image = [[UIImage alloc] initWithData:[array objectAtIndex:3]];
imageView5.image = [[UIImage alloc] initWithData:[array objectAtIndex:4]];
imageView6.image = [[UIImage alloc] initWithData:[array objectAtIndex:5]];
imageView7.image = [[UIImage alloc] initWithData:[array objectAtIndex:6]];
imageView8.image = [[UIImage alloc] initWithData:[array objectAtIndex:7]];
imageView9.image = [[UIImage alloc] initWithData:[array objectAtIndex:8]];
}
END EDIT
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(applicationDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:app];
[super viewDidLoad];
}
- (void)viewDidUnload
{
self.user = nil;
}
This way, you will not lose the images or data, they will be stored and easily accessed, and they will not disappear even if you update your app.
Cheers!
Before I start with the solution, I have to warn you that the way you're doing this isn't the right one. I suggest that you start learning iOS development from the ground up. Apple's own documentation is a pretty good start. http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/Introduction/Introduction.html
Now, back to your question. What you do here is save only one image, not all 9 of them. You set self.imageData always with each image you process and you overwrite its previous value, making only the last image to be saved to file.
So, in order to make your code working, you would have to use an imageData object for each image view, then write that data object to file.
In your case, it's probably best to optimize the code by using loops, instead using multiple objects (like imageView, imageView2, ...).
Also, make sure that you take care of your memory. e.g. imageView.image is allocated but not released.
Well, I see two issues. First and foremost, in viewDidLoad, all your images are getting initWithData:vdlData... so they're all getting the same data. That's why they're all the same.
Also, when you're trying to save them, in ...didEnterBackground, you are overwriting the value of imageData over and over again... when you save it, it's just the last one you've assigned to imageData. You probably want to create an NSArray, and store them in there, pulling them out of the array in viewDidLoad.

iOS memory management UIImage

if UIImage is an autorelease object, why when I analyze does it complain that on the 2nd line below there is a potential leak stored to image:
NSData *data = [[NSData alloc] initWithContentsOfURL: ImageURL];
UIImage *image = [[UIImage alloc] initWithData: data];
[data release];
// Do we want to round the corners?
image = [self roundCorners: image];
// Is it PNG or JPG/JPEG?
// Running the image representation function writes the data from the image to a file
if([ImageURLString rangeOfString: #".png" options: NSCaseInsensitiveSearch].location != NSNotFound)
{
[UIImagePNGRepresentation(image) writeToFile: uniquePath atomically: YES];
}
else if(
[ImageURLString rangeOfString: #".jpg" options: NSCaseInsensitiveSearch].location != NSNotFound ||
[ImageURLString rangeOfString: #".jpeg" options: NSCaseInsensitiveSearch].location != NSNotFound
)
{
[UIImageJPEGRepresentation(image, 100) writeToFile: uniquePath atomically: YES];
}
Why do you say your UIImageĀ is autoreleased? I see only
UIImage *image = [[UIImage alloc] initWithData: data];
Use instead
UIImage *image = [[[UIImage alloc] initWithData: data] autorelease];
As an alternative you may use:
UIImage *tmp = [[UIImage alloc] initWithData: data];
UIImage *image = [self roundCorners: tmp];
[tmp release];
(assuming roundCorners returns an autoreleased object).
In your code, on the second line, your UIImage isn't autoreleased. As soon as you use alloc/init methods, you're retaining. Using a convenience method like imageNamed: creates an auto released object.

UIImage error with dynamic string

I'm trying to load an image into the cell,
The following code is working correctly :
NSString *imageURL = #"http://localhost/images/image2.jpg";
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imageURL]];
UIImage *rowImage = [[UIImage alloc] initWithData:imageData];
cell.image=rowImage;
but when i change imageURL to be dynamic , the image isn't displayed :
NSString *imageURL = [[stories objectAtIndex:indexPath.row] objectForKey:#"image"];
You might be saying the problem is in :
[[stories objectAtIndex:indexPath.row] objectForKey:#"image"];
But it's not , i've tried to log it and the output is as expected :
NSSLog(#"%#",[[stories objectAtIndex:indexPath.row] objectForKey:#"image"]);
//Outputs http://localhost/images/image2.jpg
What could be wrong ?
I am guessing there is space before or after the string. So do this,
NSString *imageURL = [[stories objectAtIndex:indexPath.row] objectForKey:#"image"];
imageURL = [imageURL stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imageURL]];
UIImage *rowImage = [[UIImage alloc] initWithData:imageData];
While this should mostly fix your issue, I suggest you trim the strings before adding to the dictionary during the XML parsing.
You should also ensure you release both imageData and rowImage. You might be doing it already but its not in the code above so I just wanted to indicate that it could be leaking.
try this one
NSString *imageURL =[NSString stringWithFormat:#"%#",[[stories objectAtIndex:indexPath.row] objectForKey:#"image"]];

fetch image by using url

I want image on view by fetching it from some url. I want changing in given code..
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
UIImage *image = [[UIImage imageNamed:<#(NSString *)name#>
NSString * mediaUrl = [[[self appDelegate]currentlySelectedBlogItem]mediaUrl];
[[self image]setImage:[UIImage imageNamed:#"unknown.jpg"]];
if(nil != mediaUrl){
NSData* imageData;
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
#try {
imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:mediaUrl]];
}
#catch (NSException * e) {
//Some error while downloading data
}
#finally {
UIImage * imageFromImageData = [[UIImage alloc] initWithData:imageData];
[[self image]setImage:imageFromImageData];
[imageData release];
[imageFromImageData release];
}
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
self.titleTextView.text = [[[self appDelegate] currentlySelectedBlogItem]title];
self.descriptionTextView.text = [[[self appDelegate] currentlySelectedBlogItem]description];
}
Using this will give you a solution
NSURL *url = [NSURL URLWithString:#"ENTER YOUR URL HAVING THE IMAGE"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
I have used the following:
NSString *url=[NSString stringWithFormat:#"Your URL"];
//NSLog(#"URL=%#",url);
UIImage *myImage=[[UIImage alloc] initWithData:[NSData UIImage *myImage=[[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: url]]];
NSLog(#"%d byte of data", [[NSData dataWithContentsOfURL: [NSURL URLWithString: url]] length]);
if (myImage)
{
//THIS CODE WILL STORE IMAGE DOCUMENT DIRECTORY
NSString *jpegFilePath = [NSString stringWithFormat:#"%#/%#.jpg",[self pathForDocumentDirectory],[self.idOfImagesToDownload objectAtIndex:i]];
NSData *data1 = [NSData dataWithData:UIImageJPEGRepresentation(myImage, 1.0f)];//1.0f = 100% quality
[data1 writeToFile:jpegFilePath atomically:YES];
}
NOTE:[self pathForDocumentDirectory] is method returning path of document directory.

how to compress image programmatically

I am receiving images from xml feed they are very large in size how can i compress them before displaying them in table-cell.
my code is
int blogEntryIndex1 = [indexPath indexAtPosition: [indexPath length] -1];
imgstring=[[blogEntries objectAtIndex: blogEntryIndex1] objectForKey: #"image"];
NSURL *url = [NSURL URLWithString:imgstring];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
cell.imageView.image=[img autorelease];
please help me if you can.....
I've got this utility method that will scale an image :
- (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize {
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Use it like this :
int blogEntryIndex1 = [indexPath indexAtPosition: [indexPath length] -1];
imgstring=[[blogEntries objectAtIndex: blogEntryIndex1] objectForKey: #"image"];
NSURL *url = [NSURL URLWithString:imgstring];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [self imageWithImage:[UIImage imageWithData:data] scaledToSize:CGSizeMake(20, 20)]; // Scale it to 20x20px
cell.imageView.image=[img autorelease];
NB I can't for the life of me remember where I got it from but it's served me well in the past
Simple to use:-
-(UIImage *)fireYourImageForCompression:(UIImage *)imgComing{
NSData *dataImgBefore = [[NSData alloc] initWithData:UIImageJPEGRepresentation((imgComing), 1.0)];//.1 BEFORE COMPRESSION
int imageSizeBefore = (int)dataImgBefore.length;
NSLog(#"SIZE OF IMAGE: %i ", imageSizeBefore);
NSLog(#"SIZE OF IMAGE in Kb: %i ", imageSizeBefore/1024);
NSData *dataCompressedImage = UIImageJPEGRepresentation(imgComing, .1); //.1 is low quality
int sizeCompressedImage = (int)dataCompressedImage.length;
NSLog(#"SIZE AFTER COMPRESSION OF IMAGE: %i ", sizeCompressedImage);
NSLog(#"SIZE AFTER COMPRESSION OF IMAGE in Kb: %i ", sizeCompressedImage/1024); //AFTER
//now change your image from compressed data
imgComing = [UIImage imageWithData:dataCompressedImage];
return imgComing;}