How to programmatically set the background on a UICustomButton? - iphone

I know this question has been asked and answered in other forums, but I can't seem to duplicate what they did and get it to work. I am trying to set the background to a button using a picture that I download from a server. Everything works until I try to make a NSData object with the contents of a URL. When I try and print the Data to the screen it comes back Null. What am I doing wrong?
myImageURLString = [[NSMutableString alloc] initWithString:#"http://destinationnexus.com"];
keyName = [businessButtonTagArray objectAtIndex:i];
arrayFromBusinessDictionary = [businessDictionary objectForKey:keyName];
stringToAddToMyImageURLString = [arrayFromBusinessDictionary objectAtIndex:1];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[button setTag:i];
button.frame = CGRectMake(xOffSet+(countForX*xMult), yOffset +(countForY*yMult), 215, 155);
[myImageURLString appendString:stringToAddToMyImageURLString];
NSLog(#"Appended URL String: = %#", myImageURLString);
NSURL *myImageURL = [NSURL URLWithString:#"http://destinationnexus.com/pictures/directory/ColdWater-Inn-in-Tuscumbia-Alabama-35674-8729//.jpg"];
NSLog(#"NSURL = %#", myImageURL);
//THIS IS WHERE I SEEM TO HAVE A PROBLEM.....
NSData *imageData = [[NSData alloc] initWithContentsOfURL:myImageURL];
UIImage *image = [[UIImage alloc] initWithData:imageData] ;
NSLog(#"Image Data = %#", imageData);
//UIImage *myImage = [UIImage imageWithData:imageData] ;
[button setBackgroundImage:image forState:UIControlStateNormal];
When I run the program this is what it outputs in the Log:
Appended URL String: = http://destinationnexus.com/pictures/directory/Auburn-University-Hotel-and-Center-in-Auburn-Alabama-36830-5429.jpg
NSURL = http://destinationnexus.com/pictures/directory/ColdWater-Inn-in-Tuscumbia-Alabama-35674-8729.jpg
Image Data = (null)

You should correct your myImageURL, by deleting 2 slashes at the end of URL.
The code goes something like this.
NSURL *myImageURL = [NSURL URLWithString:#"http://destinationnexus.com/pictures/directory/ColdWater-Inn-in-Tuscumbia-Alabama-35674-8729.jpg"];
NSData *imageData = [[NSData alloc] initWithContentsOfURL:myImageURL];
UIImage *image = [[UIImage alloc] initWithData:imageData] ;
[button setBackgroundImage:image forState:UIControlStateNormal];
[image release];
[imageData release];

Related

How to show image loaded from a url on a button?

Here is an example :
Show multi image on multi button and show on scrollview
(void)viewDidLoad
{
[super viewDidLoad];
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
InitData *inData=[[InitData alloc]init];
scrollview.delegate=self;
scrollview.scrollEnabled = YES;
int scrollWidth = 120;
scrollview.contentSize = CGSizeMake(scrollWidth,100);
int xOffset = 0;
//imageView.image = [UIImage imageNamed:[imagesName objectAtIndex:0]];
//Test
NSURL *url=[NSURL URLWithString:#"....."];
NSData *jsonData=[NSData dataWithContentsOfURL:url];
if (jsonData !=nil)
{
NSError *error=nil;
id result=[NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
if (error ==nil)
{
NSLog(#"%#",result);
// NSMutableArray *ArImg = nil;
NSArray* rus=[result objectForKey:#"RespOBJ"];
for (int index = 0; index < rus.count ; index++)
{
NSMutableDictionary* final=[rus objectAtIndex:index];
[inData setId:(int)[final objectForKey:#"Id"]];
[inData setTum:[final objectForKey:#"TumbImage"]];
[inData setImage:[final objectForKey:#"Image"]];
UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
[btn setImage:[UIImage imageNamed:[inData getImage]] forState:(UIControlStateNormal)];
//[btn setImage:[UIImage imageWithData:jsonData] forState:(UIControlStateNormal)];
[btn setTag:index];
btn.bounds = CGRectMake(10, 10, 50, 50);
btn.frame = CGRectMake(5+xOffset, 0, 160, 70);
scrollview.contentSize = CGSizeMake(scrollWidth+xOffset,70);
NSLog(#"%#",[inData getId]);
NSLog(#"%#",[inData getImage]);
NSLog(#"%#",[inData getTum]);
[btn addTarget:self
action: #selector(btnclick:)
forControlEvents: UIControlEventTouchDown];
[scrollview addSubview:btn];
xOffset += 170;
}
The problem with your code is that you are not loading anything. I assume you want to download the image from the Internet and then display it on the scrollview. To do so, you have to use a NSURLRequest and a NSURLConnection.
Have a look at Apple's documentation https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/Reference/Reference.html and https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html
You might also like this question on how to load data asynchronously Object-c/iOS :How to use ASynchronous to get a data from URL?

Load qr code from url and display as image view

As the title says I'm trying to take a qr code like this - http://chart.apis.google.com/chart?cht=qr&chs=200x200&chl=044779-A55W6UZD&chld=H|0 and display it as a UIImageview. I've searched but couldn't find an answer anywhere. Please help.
I've tried this but it doesn't seem to work
NSData *receivedData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
UIImage *image = [[UIImage alloc] initWithData:receivedData];
UIImageView * myImageView = [[UIImageView alloc] initWithImage:image];
myImageView.frame = CGRectMake(20, 160, 200, 200);
[self.view addSubview:myImageView];
Try encoding the url like this and then use encodedUrl in the rest of the code:
NSString* encodedUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
You should also remember to release the objects you created, otherwise you leak memory.
NSData* receivedData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:encodedUrl]];
UIImage* image = [[UIImage alloc] initWithData:receivedData];
UIImageView* myImageView = [[UIImageView alloc] initWithImage:image];
myImageView.frame = CGRectMake(20, 160, image.size.width, image.size.height;
[self.view addSubview:myImageView];
[receivedData release];
[image release];
[myImageView release];

How to Importing image from server and arrange it in a view

I need to get array of images that have to call from server and arrange that in an order.But while executing below code i can't get it...Guidance please...
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
NSURL *url = [NSArray arrayWithObjects:[NSURL URLWithString:
#"http://images.wikia.com/marvelmovies/images/5/5e/The-hulk-2003.jpg"],
[NSURL URLWithString:#"http://cdn.gottabemobile.com/wp-content/uploads/2012/06/ios62.jpg"],
[NSURL URLWithString:#"http://challenge.roadef.org/2012/img/google_logo.jpg"],
[NSURL URLWithString:#"http://addyosmani.com/blog/wp-content/uploads/2012/03/Google-doodle-of-Richard-007.jpg"],
[NSURL URLWithString:#"http://techcitement.com/admin/wp-content/uploads/2012/06/apple-vs-google_2.jpg"],
[NSURL URLWithString:#"http://www.andymangels.com/images/IronMan_9_wallpaper.jpg"],
[NSURL URLWithString:#"http://sequelnews.com/wp-content/uploads/2011/11/iphone_5.jpg"],Nil];
/*
int i=0;
int cord_x=0;
int cord_y=30;
int cont=0;
for (i = 0; i < [(NSArray*)url count]; i++) {
cont=cont+1;
if (cont > 3) {
cord_x=0;
cord_y=cord_y+110;
cont=1;
}*/
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:(NSURL*)[(NSArray*)url objectAtIndex:index]]];
//cord_x=cord_x+110;
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0, 0, 200.0f, 200.0f);
[button setImage:(UIImage*)[image objectAtIndex:index] forState:UIControlStateNormal];
[button addTarget:self action:#selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
return button;
}
//}
now i need to place button image and image from server...
You can try to use NSURLConnection to download images asynchronous which will make your UI much more responsive. Just setup separate connection for each image and update images on the buttons in delegate method - connectionDidFinishLoading. It will also help you to track downloading errors (e.g. timeouts etc.).
Here is a great example with downloads images for table - you can find there a lot of help for your case:
http://developer.apple.com/library/ios/#samplecode/LazyTableImages/Introduction/Intro.html
int row = 0;
int column = 0;
for(int i = 0; i < url.count; ++i) {
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:(NSURL*) [(NSArray*)url objectAtIndex:i]]];
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(column*100+16, row*90, 80, 80);
[button setImage:image forState:UIControlStateNormal];
[button addTarget:self
action:#selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[self.view addSubview:button];
if (column == 2) {
column = 0;
row++;
} else {
column++;
}
}
NSMutableArray *arrayList=[[NSMutableArray alloc] initWithObjects:#"www.xxx.com/imag.jpg",#"www.xxx.com/img1.jpg",nil];
for(int i=0; i<[arrayList count]; i++)
{
NSURL *url = [NSURL URLWithString:[arrayList ObjetAtIndex:i]];
NSData *data = [NSData dataWithContentsOfURL: url];
UIImage *img=[UIImage imageWithData:data]; // Here is your image
}
NSURL *url = [NSArray arrayWithObjects:[NSURL URLWithString:#"http://mobiledevelopertips.com/images/logo-iphone-dev-tips.png"],[NSURL URLWithString:#"http://cdn.gottabemobile.com/wp-content/uploads/2012/06/ios62.jpg"],[NSURL URLWithString:#"http://cdn.gottabemobile.com/wp-content/uploads/2012/06/ios62.jpg"],[NSURL URLWithString:#"http://cdn.gottabemobile.com/wp-content/uploads/2012/06/ios62.jpg"],[NSURL URLWithString:#"http://cdn.gottabemobile.com/wp-content/uploads/2012/06/ios62.jpg"],[NSURL URLWithString:#"http://cdn.gottabemobile.com/wp-content/uploads/2012/06/ios62.jpg"],[NSURL URLWithString:#"http://cdn.gottabemobile.com/wp-content/uploads/2012/06/ios62.jpg"],Nil];
int i=0;
int cord_x=0;
int cord_y=30;
int cont=0;
for (i = 0; i < [(NSArray*)url count]; i++)
{
cont=cont+1;
if (cont > 3)
{
cord_x=0;
cord_y=cord_y+110;
cont=1;
}
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:(NSURL*)[(NSArray*)url objectAtIndex:i]]];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(cord_x, cord_y, 100, 100)];
[imageView setImage:image];
[self.view addSubview:imageView];
cord_x=cord_x+110;
}

I can't see any picture. Why?

I can't see any picture. Why?
UIImage *photoImg = [UIImage imageNamed:#"http://blog.leadcritic.com/wp-content/uploads/2011/02/favorite_animal_picture.jpg"];
UIImageView *imageView2 = [[UIImageView alloc] initWithImage:photoImg];
[self.view addSubview:imageView2];
Because if you use the code:
[UIImage imageNamed:#"mypicture.png"];
The image should be on the iPhone and not loaded from a URL. From a URL you need to use the following:
NSString path = #"http://blog.leadcritic.com/wp-content/uploads/2011/02/favorite_animal_picture.jpg";
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *photoImg = [[UIImage alloc] initWithData:data cache:NO];
UIImageView *imageView2 = [[UIImageView alloc] initWithImage:photoImg];
You haven't set the frame of imageView2
imageView2.frame = CGRectMake( 0, 0, 100, 100 ); // Or whatever.

Xcode iPhone Programming: Loading a jpg into a UIImageView from URL

My app has to load an image from a http server and displaying it into an UIImageView
How can i do that??
I tried this:
NSString *temp = [NSString alloc];
[temp stringwithString:#"http://192.168.1.2x0/pic/LC.jpg"]
temp=[(NSString *)CFURLCreateStringByAddingPercentEscapes(
nil,
(CFStringRef)temp,
NULL,
NULL,
kCFStringEncodingUTF8)
autorelease];
NSData *dato = [NSData alloc];
dato=[NSData dataWithContentsOfURL:[NSURL URLWithString:temp]];
pic = [pic initWithImage:[UIImage imageWithData:dato]];
This code is in viewdidload of the view but nothing is displayed!
The server is working because i can load xml files from it. but i can't display that image!
I need to load the image programmatically because it has to change depending on the parameter passed!
Thank you in advance.
Antonio
It should be:
NSURL * imageURL = [NSURL URLWithString:#"http://192.168.1.2x0/pic/LC.jpg"];
NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage * image = [UIImage imageWithData:imageData];
Once you have the image variable, you can throw it into a UIImageView via it's image property, ie:
myImageView.image = image;
//OR
[myImageView setImage:image];
If you need to escape special characters in your original string, you can do:
NSString * urlString = [#"http://192.168.1.2x0/pic/LC.jpg" stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL * imageURL = [NSURL URLWithString:urlString];
....
If you're creating your UIImageView programmatically, you do:
UIImageView * myImageView = [[UIImageView alloc] initWithImage:image];
[someOtherView addSubview:myImageView];
[myImageView release];
And because loading image from URL takes ages, it would be better to load it asynchronously. The following guide made it stupid-simple for me:
http://www.switchonthecode.com/tutorials/loading-images-asynchronously-on-iphone-using-nsinvocationoperation
Try this
NSURL *url = [NSURL URLWithString:#"http://192.168.1.2x0/pic/LC.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImageView *subview = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f,320.0f, 460.0f)];
[subview setImage:[UIImage imageWithData:data]];
[cell addSubview:subview];
[subview release];
All the Best.
This is the actual code.
UIImageView *myview=[[UIImageView alloc]init];
myview.frame = CGRectMake(0, 0, 320, 480);
NSURL *imgURL=[[NSURL alloc]initWithString:#"http://soccerlens.com/files/2011/03/chelsea-1112-home.png"];
NSData *imgdata=[[NSData alloc]initWithContentsOfURL:imgURL];
UIImage *image=[[UIImage alloc]initWithData:imgdata];
myview.image=image;
[self.view addSubview:myview];
You should load the image in the background or the view will freeze.
Try this:
UIImage *img = [[UIImage alloc] init];
dispatch_async(dispatch_get_global_queue(0,0), ^{
NSData * data = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:#"http://www.test.com/test.png"];
img = [UIImage imageWithData: data];
dispatch_async(dispatch_get_main_queue(), ^{
//PUT THE img INTO THE UIImageView (imgView for example)
imgView.image = img;
});
});