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
Related
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.
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"]];
}
Im trying to load the image of my uitableviewcells in lazy mode.
I'm trying to do it in the simplest possible way, I saw a lot of examples but they were going further than my purpose.
This is what Im doing currently, and its not working:
// Configure the cell...
Info *info = [self.Array objectAtIndex:indexPath.row];
cell.textLabel.text = info.name;
cell.detailTextLabel.text = info.platform;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//The image is downloaded in asynchronous
NSBlockOperation *downloadingImgBlock = [NSBlockOperation blockOperationWithBlock:^{
NSString* imageURL = info.imgURL;
NSData* imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:imageURL]];
cell.imageView.image = [UIImage imageWithData:imageData];
}];
[self.queue addOperation:downloadingImgBlock];
Why it's not working? And how could it work?
Man, AsyncImageView is your friend! Just set the image url and everything is handled for you, downloading, caching. It's awesome.
Try the following codes
......
__block UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
__block UIImage *img;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString: imageURL]]];
dispatch_async(dispatch_get_main_queue(),^{
cell.imageView.image = img;
}
});
});
......
Using the 3rd party library source code would be easiest, but here's how you would do it in code. You are going to want to make a NSMutableArray either as a property in your .h or at the top of your .m like this:
#implementation viewController{
NSMutableArray *picList;
}
and in -initWithCoder: or, whatever init you are overloading:
picList = [[NSMutableArray alloc] init];
in – tableView:cellForRowAtIndexPath: (fullPicURL is the URL):
if([self imageExists:fullPicURL]){
shoePic = [picList objectForKey:fullSmallPicURL];
} else {
NSURL *picURL = [NSURL URLWithString:fullPicURL];
shoePic = [UIImage imageWithData:[NSData dataWithContentsOfURL:picURL]];
NSDictionary *thisImage = [NSDictionary dictionaryWithObject:shoePic forKey:fullSmallPicURL];
[cachedImages addEntriesFromDictionary:thisImage];
}
where -imageExists: is a function you write which checks the dictionary for the url. The object is the picture itself, the key is the url. Then you do cell.image = showPic;, or whatever you want to call it, and you're done for cacheing. In order to load them asynchronously, do this:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *data = [NSData dataWithContentsOfURL:shoes];
[self performSelectorOnMainThread:#selector(fetchedShoeData:) withObject:data waitUntilDone:YES];
});
and at the end of fetchedData:
[self.tableView reloadData];
then just make sure you edit –numberOfSectionsInTableView: to change itself if it has to. Might be some other things you need to do to get it working 100%, let me know
try this one, I'm using always this scheme to load images asynchronously:
(I haven't found simplest way.)
- (void)inAnyMethod {
// ...
void (^blockLoadPhoto)() = ^{
UIImage *_imageTemporary = [UIImage imageNamed:#"..."];
if (_imageTemporary) {
[self performSelectorOnMainThread:#selector(setPhoto:) withObject:_imageTemporary waitUntilDone:true];
}
};
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), blockLoadPhoto);
// ...
}
- (void)setPhoto:(UIImage *)photo {
// do something with the loaded image
}
I finally managed to do it setting the image with:
– performSelectorOnMainThread:withObject:waitUntilDone:
After the image is downloaded
Is it possible to read a url to an image and set a UIImageView to the image at this url?
For such a straightforward task I would highly recommend against integrating projects such as Three20, the library is a monster and not very straightforward to get up and running.
I would instead recommend this approach:
NSString *imageUrl = #"http://www.foo.com/myImage.jpg";
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:imageUrl]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
myImageView.image = [UIImage imageWithData:data];
}];
EDIT for Swift 3.0
let urlString = "http://www.foo.com/myImage.jpg"
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print("Failed fetching image:", error)
return
}
guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
print("Not a proper HTTPURLResponse or statusCode")
return
}
DispatchQueue.main.async {
self.myImageView.image = UIImage(data: data!)
}
}.resume()
*EDIT for Swift 2.0
let request = NSURLRequest(URL: NSURL(string: urlString)!)
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in
if error != nil {
print("Failed to load image for url: \(urlString), error: \(error?.description)")
return
}
guard let httpResponse = response as? NSHTTPURLResponse else {
print("Not an NSHTTPURLResponse from loading url: \(urlString)")
return
}
if httpResponse.statusCode != 200 {
print("Bad response statusCode: \(httpResponse.statusCode) while loading url: \(urlString)")
return
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.myImageView.image = UIImage(data: data!)
})
}.resume()
NSString *ImageURL = #"YourURLHere";
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
imageView.image = [UIImage imageWithData:imageData];
It's possible to load an NSData from a URL and convert that to an image and stick that in the image view, but this is an extremely bad idea because it involves doing a synchronous URL download on the main thread. This will lock up the UI and possibly cause the user to think your app has crashed if the image doesn't download extremely fast.
Edit: To clarify, the original question looks to me like the poster wants to say something along the lines of
imageView.image = [UIImage imageWithContentsOfURL:theURL];
Hence my answer. It's possible to do the equivalent by going through NSData, but it's a bad idea. Instead, the image should be downloaded asynchronously using NSURLConnection, and only once it's fully downloaded should it be converted into a UIImage and assigned to the image view.
I am using https://github.com/rs/SDWebImage which is a beautifully designed library, which has the options to put a placeholder image, whether to memory, or disk cache the image or use the downloader independent of a UIImageView.
I was trying to do that by myself but the library took all the pain away.
All you need to do is to write the code below for your case :
#import "UIImageView+WebCache.h"
[imageView sd_setImageWithURL:[NSURL URLWithString:#"http://www.domain.com/path/to/image.jpg"] placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
Worked like a charm for me.
If you want to display image from Url in ImageView, And also want to save this image in cache for optimize to server interaction this would help you Just pass your imageView object and string Url to this function
-(void)downloadingServerImageFromUrl:(UIImageView*)imgView AndUrl:(NSString*)strUrl{
strUrl = [strUrl encodeUrl];
NSString* theFileName = [NSString stringWithFormat:#"%#.png",[[strUrl lastPathComponent] stringByDeletingPathExtension]];
NSFileManager *fileManager =[NSFileManager defaultManager];
NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"tmp/%#",theFileName]];
imgView.backgroundColor = [UIColor darkGrayColor];
UIActivityIndicatorView *actView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
[imgView addSubview:actView];
[actView startAnimating];
CGSize boundsSize = imgView.bounds.size;
CGRect frameToCenter = actView.frame;
// center horizontally
if (frameToCenter.size.width < boundsSize.width)
frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
else
frameToCenter.origin.x = 0;
// center vertically
if (frameToCenter.size.height < boundsSize.height)
frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2;
else
frameToCenter.origin.y = 0;
actView.frame = frameToCenter;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSData *dataFromFile = nil;
NSData *dataFromUrl = nil;
dataFromFile = [fileManager contentsAtPath:fileName];
if(dataFromFile==nil){
dataFromUrl=[[[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:strUrl]] autorelease];
}
dispatch_sync(dispatch_get_main_queue(), ^{
if(dataFromFile!=nil){
imgView.image = [UIImage imageWithData:dataFromFile];
}else if(dataFromUrl!=nil){
imgView.image = [UIImage imageWithData:dataFromUrl];
NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"tmp/%#",theFileName]];
BOOL filecreationSuccess = [fileManager createFileAtPath:fileName contents:dataFromUrl attributes:nil];
if(filecreationSuccess == NO){
NSLog(#"Failed to create the html file");
}
}else{
imgView.image = [UIImage imageNamed:#"NO_Image.png"];
}
[actView removeFromSuperview];
[actView release];
[imgView setBackgroundColor:[UIColor clearColor]];
});
});
}
Here's an updated answer to the best answer, as imageWithContentsOfURL is no longer a method of UIImage. You'll have to use CIImage:
NSURL *url = [NSURL URLWithString:#"http://url_goes_here.com/logo.png"];
imageView.image = [UIImage imageWithCIImage:[CIImage imageWithContentsOfURL:url]];
Unfortunately this feature is not available as of this writing... instead you will have to implement the functionality yourself by:
Downloading the data of the image
Saving it or caching it somewhere (db or filesystem) and then
Setting the UIImaveView to the saved structure
Fortunately you don't have to break your head coming out with said functionality as Apple provides an example that does exactly that as part of their code samples.
Follow the code and I'm sure you will be able to accommodate it to your needs.
EGOImageLoading
EGOImageView* imageView = [[EGOImageView alloc] initWithPlaceholderImage:[UIImage imageNamed:#"placeholder.png"]];
imageView.frame = CGRectMake(0.0f, 0.0f, 36.0f, 36.0f);
//show the placeholder image instantly
[self.anyView addSubview:imageView];
[imageView release] //if you want
//load the image from url asynchronously with caching automagically
imageView.imageURL = [NSURL URLWithString:photoURL];
If you want more, there is a delegate to handle actions after loading
#protocol EGOImageViewDelegate<NSObject>
#optional
- (void)imageViewLoadedImage:(EGOImageView*)imageView;
- (void)imageViewFailedToLoadImage:(EGOImageView*)imageView error:(NSError*)error;
#end
Another option is TTImageView from the Three20 library which handles asynchronous loading of an image. The control works great. However, the downside is you have to deal with the nightmare of installing Three20 (which is then almost impossible to fully remove).
use AFNetworking category UIImageView+AFNetworking.h
#import "UIImageView+AFNetworking.h
[profileImageView setImageWithURL:[NSURL URLWithString:photoURL] placeholderImage:[UIImage imageNamed:#"placeholder"]];
I've got some code to load an image from a URL, it seems to work ok. Unless the URL contains curly brackets. This seems like it is a string formatting problem? I can't figure it out.
ex
#"http://site/image.png //works
#"http://site/{image}.png //doesn't work
NSString* mapURL = #"http://site.com/directory/{map}.png";
NSLog(mapURL);
NSData* imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:mapURL]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
[imageView setImage:image];
[imageData release];
[image release];
thanks
i found this helpful
http://simonwoodside.com/weblog/2009/4/22/how_to_really_url_encode/