Display Image to UIImageView which comes from Server - iphone

I am getting strange issue please if get help from anyone then it'll be appreciated.
My problem is i am getting only Image names from server through web service for ex: abc.png.
Now that image need to be attached with the static URL & than it will be used to display to UIImageView.
I have used this code:
for (int i = 0; i<[[myDic valueForKey:#"posts"] count]; i++)
{
NSData *bgImageData = nil;
if ([[[[myDic valueForKey:#"posts"] objectAtIndex:i] valueForKey:#"post"] valueForKey:#"video_image"] == [NSNull null])
{
bgImageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://drupal.org/files/issues/no-pre.png"]];
}
else
{
bgImageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://sitebildz.com/application/document/video/%#",[[[[myDic valueForKey:#"posts"] objectAtIndex:i] valueForKey:#"post"] valueForKey:#"video_image"]]]];
}
[arrVideoImage addObject:bgImageData];
}
For Display in Table :
cell.imageView.image = [UIImage imageWithData:[arrVideoImage objectAtIndex:indexPath.row]];
But don't know why its not working.
Thanks.

As commented The Tiger, your best choice would be to use an external library like SDWebImage which can handle download, caching and display of online images.
Here is an example using this framework :
[imageView setImageWithURL:[NSURL URLWithString:#"http://www.domain.com/path/to/image.jpg"]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
You can also use blocks to insert logic once an image finished loading :
[cell.imageView setImageWithURL:[NSURL URLWithString:#"http://www.domain.com/path/to/image.jpg"]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {... completion code here ...}];

You're doing wrong. See you're making NSData in loop. Do you think it will wait until image is download from server ??? Nope it will not wait. So in this case you're adding empty NSData.
Would be better to use SDWebImage.
1. Download it
2. Import it in your project
3. build project (success)
4. Import #import "UIImageView+WebCache.h" in your ViewController class
[cell.imageView setImageWithURL:imageURL placeholderImage:[UIImage imageNamed:#"placeHolderImageName"]];

you cab use https://github.com/enormego/EGOImageLoading/tree/master/EGOImageView which will download the image from server in async way and display once it completely downloaded from server. It also cache that image so that multiple request can be avoided and it enhances the system.

Related

Taking time to load the image from URL to UIImageview

I am using this code for displaying the image from URL to UIImageview
UIImageView *myview=[[UIImageView alloc]init];
myview.frame = CGRectMake(50, 50, 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];
But the problem is that its taking too long time to display the image in imageview.
Please help me...
Is there any method to fast the process...
Instead of dispatch_async, Use SDWebImage for caching the images.
This is best I have seen...
The problem of dispatch_async is that if you lost focus from image, it will load again. However SDWebImage, Caches the image and it wont reload again.
The answers given to me on my own question Understanding the behaviour of [NSData dataWithContentsOfURL:URL] inside the GCD block does makes sense.So be sure that if you use [NSData dataWithContentsOfURL:URL] inside the GCD(as many developers do these days) is not a great idea to download the files/images.So i am leaning towards the below approach(you can either use NSOperationQueue).
Load your images using [NSURLConnection sendAsynchronousRequest:queue:completionHandler: then use NSCache to prevent downloading the same image again and again.
As suggested by many developers go for SDWebimage and it does include the above strategy to download the images files .You can load as many images you want and the same URL won't be downloaded several times as per the author of the code
EDIT:
Example on [NSURLConnection sendAsynchronousRequest:queue:completionHandler:
NSURL *url = [NSURL URLWithString:#"your_URL"];
NSURLRequest *myUrlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:myUrlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] > 0 && error == nil)
//doSomething With The data
else if (error != nil && error.code == ERROR_CODE_TIMEOUT)
//time out error
else if (error != nil)
//download error
}];
Use Dispatch queue to load image from URL.
dispatch_async(dispatch_get_main_queue(), ^{
});
Or add a placeholder image till your image gets load from URL.

Get image from a php file to iOS

I want to get image from a php file (for example: http://abc.xyz.com/api/showImage.php) for a specific user through the user id & set the image in the image view of my iOS app. How can i do so?
Thanks in advance.
You can get the image from the above URL in the form of NSData :
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL urlWithString:#"http://abc.xyz.com/api/showImage.php"]];
UIImageView *imageView = [UIImageView alloc] initWithImage:[UIImage imageWithData:imageData]];
Its better to use Asyn download method when displaying images from the web.
You could create your own category on UIImageView or use the popular ones out there
SDWebImage.
[imageView setImageWithURL:[NSURL URLWithString:#"http://www.domain.com/path/to/image.jpg"]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
Store response into array and then into an object say profile Object.I am using SDWebImage.
if U are geting image url at detailsObj.profileImage.Then use like below to set to imageview..
NSLog(#"response is:%#",userDetailsArray);
ProfileObject *detailsObj=[userDetailsArray objectAtIndex:0];
//in place of detailsObj.profileImage use url server link which is getting image.
if([detailsObj.profileImage isEqualToString:#""] || [detailsObj.profileImage isKindOfClass:[NSNull class]] || detailsObj.profileImage.length==0)
{
self.profileImageView.image=[UIImage imageNamed:#"NoImage.png"];
}
else
{
//without using SDWebImage
[self.profileImageView setImageWithURL:[NSURL URLWithString:detailsObj.profileImage]];
//if it is NSData getting from server
self.profileImageView.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL urlWithString:detailsObj.profileImage]]];
//or using SDWebImage
[self.profileImageView setImageWithURL:[NSURL URLWithString:detailsObj.profileImage] placeholderImage:[UIImage imageNamed:#"NoImage.png"]];
}

SDWebImage always load the placeholder image not the image from URL

Um using the SDWeb image Here
and these my Code :
UIImageView *sellerImage = [[UIImageView alloc]init];
[sellerImage setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:productPicture]]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
but it always load the placeholder image only not the image from URL,
I've tried to use blocks to make sure if it load's the image or not and it enter to the Success Block which means that SDWebImage can load the image from URL but it doesn't change the place holder image.
These is the code When I tried to use blocks :
[sellerImage setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:productPicture]]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]
success:^(UIImage *image, BOOL cached)
{
NSLog(#"success Block");
}
failure:^(NSError *error)
{
NSLog(#"failure Block");
}];
As I said it always goes in the success Block which means it can load the image from URL but it doesn't change the place holder image.
and these is a screen from my problem.
also try the following
[sellerImage setImageWithURL:[NSURL URLWithString:[productPicture stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]
success:^(UIImage *image, BOOL cached)
{
dispatch_async(dispatch_get_main_queue(), ^{
sellerImage.image = image;
});
NSLog(#"success Block");
}
failure:^(NSError *error)
{
NSLog(#"failure Block");
}];
try the following
UIImageView *sellerImage = [[UIImageView alloc]init];
[sellerImage setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:
[productPicture stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
Assign a placeholder image properly.. issue with me was with wrong image extension that doesn't match with each other i.e. placeholder.jpeg and palceholder#2x.jpg

Integrating SDWebImage With YouTube Api

I am Trying to integrate SdWebImage With Youtube Api for the purpose of Fetching thumbnail image to cache them so as get rid of scrolling problem in UITableView.Problem is Youtube API Provide a URL that is for Thumbnail NSDATA which can be converted back to UIImage object but SDWebImage is Takes URL to an image to manage images in best efficient method.
Youtube Api Method:
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[thumbnails objectAtIndex:0] URLString]]];
UIImage * image = [UIImage imageWithData:data];
SDWebImage Method
[cell.imageView setImageWithURL:[NSURL URLWithString:[_objects objectAtIndex:indexPath.row]]
placeholderImage:[UIImage imageNamed:#"placeholder"]];
Please Tell How We Solve this Problem.
I think you are overthinking this problem. You should be able to just do this:
NSURL *thumbnailURL = [NSURL URLWithString:[[thumbnails objectAtIndex:indexPath.row] URLString]]];
[cell.imageView setImageWithURL:thumbnailURL
placeholderImage:[UIImage imageNamed:#"placeholder"]];

unable to display image using SDWebImage

Newbie to iPhone here.
I have an image to display fetched from a rss feed. I'm currently using the code below which works but slows down loading elements in the view:
for(int i=0; i<[bannerArray count]; i++){
NSString *bannerImagestr = [[bannerArray objectAtIndex:i] BannerImage];
bannerImagestr = [ bannerImagestr stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSURL *banURL= [NSURL URLWithString:bannerImagestr];
NSData *data = [NSData dataWithContentsOfURL:banURL];
imgEventDetail = [[[UIImage alloc] initWithData:data] autorelease];
[banEventDetailArray addObject:imgEventDetail];
}NSLog(#"the banEventDetailArray is %#",banEventDetailArray);
I tried the SDWebImage api to make it load quick but i'm failing to get the image. The code which i've been using is below:
for(int i=0; i<[bannerArray count]; i++){
NSString *bannerImagestr = [[bannerArray objectAtIndex:i] BannerImage];
bannerImagestr = [ bannerImagestr stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSURL *banURL= [NSURL URLWithString:bannerImagestr];
[banIconImage setImageWithURL:banURL placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
banImg=banIconImage.image;//<<<-------- updated here banImg is an instance of UIImage
[banEventDetailArray addObject:banImg];
}NSLog(#"the banEventDetailArray is %#",banEventDetailArray);
I need the banEventDetailArray in the form of UIImage, because I'm setting this array in the below code which takes (UIImage *) as its parameter
[eventsdetailroundedButtonType setBackgroundImage:[banEventDetailArray objectAtIndex:numTimerTicks] forState:UIControlStateNormal];
Please help me find what I've been missing out and where I may have gone wrong.
Thanks in advance.
UPDATE: i've replaced a line in the second code block. i.e. banImg=banIconImage.image; at line number 11.
You can use your image URL as key to find the cached image:
UIImage *myCachedImage = [[SDImageCache sharedImageCache] imageFromKey:[NSString \
stringWithFormat:#"%#",banURL]];
I guess the problem is in this lines:
[banIconImage setImageWithURL:banURL placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
banImg=[[UIImage alloc]init]; // <-- here: empty image
[banIconImage setImage:banImg]; // <-- here: overriding banURL image
since you are:
first, getting the image from the URL;
overriding that image with an empty one.
Use this code, instead:
[banIconImage setImageWithURL:banURL placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
[banEventDetailArray addObject:banIconImage];
i.e., you add the image your retrieve to the array and then use it later.
You need to keep track of the UIImageView because it is where the SDWebImage magics happens. Indeed, that view handles the displays of the placeholder while the image is fetched; when the image is there, it is replaced.
You can get the image property only after the actual image is fetched, otherwise you will only get the placeholder.
Why are you setting the image twice? Doesn't make sense.
[banIconImage setImageWithURL:banURL placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
banImg=[[UIImage alloc]init];
[banIconImage setImage:banImg];
Try removing the second setting, should just be.
[banIconImage setImageWithURL:banURL placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
EDIT: Logic still doesn't make sense. You're probably trying add the UIImageView's image as an object in the array, which means your code should probably look like this.
NSString *bannerImagestr = [[bannerArray objectAtIndex:i] BannerImage];
bannerImagestr = [ bannerImagestr stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSURL *banURL= [NSURL URLWithString:bannerImagestr];
[banIconImage setImageWithURL:banURL placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
[banEventDetailArray addObject:banIconImage.image];
Try the code before you decide it's not what you need, apparently you don't exactly know what you want. If this is the answer to your question, mark it as the solution.
Your array does not hold image object. Instead it hold pointers (references) to UIImage objects. If you look at your working code, there you have:
imgEventDetail = [[[UIImage alloc] initWithData:data] autorelease];
[banEventDetailArray addObject:imgEventDetail];
You create and add new instance of imgEventDetail UIImage object with data and then add it to the array. You would need to do the same for your bottom (not working) code.
Try this in the not working code:
[banEventDetailArray addObject:banIconImage.image]; // array automatically retains.
All assuming that your images are downloaded correctly using SDWebImage API.