Set UIImageView using URL - ios

I am setting image in UIImageView using:
[self.imageView setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:[UIImage imageNamed:#"random_image"]];
I am able to see the image on phone as expected.
However, if I use the method without placeholder argument
[self.imageView setImageWithURL:[NSURL URLWithString:urlString]];
OR pass the placeholderImage as nil
[self.imageView setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:nil];
then the image is not set and my imageView is blank. I understand that placeholder image is for "representing the current state of the asset suitable for temporarily displaying in your extension’s UI.".
I don't understand how its absence should impact me the way it is impacting. Any pointers?

If you set default placeholder image then imageview gets width and night.Otherwise imageview frame is may be (0,0).
Or
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
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:imageUrl]] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
ImageViewName.image = [UIImage imageWithData:data];
}];

I found the issue. I added an image view in UITableViewCell with the name imageView. Apparently, UITableViewCell already has a property with the same name. I changed the name of myImageView to cellImageView and now, I don't need the placeholder parameter anymore! Having said that, I still don't understand what happened behind the screens!

i hope these code will help u....
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:
[NSURL URLWithString:#“image URL”]]];
dispatch_sync(dispatch_get_main_queue(), ^{
[[cell myimage] setImage:image];
}
});
});

Related

Loading an image from web-service on to an UIImage doesn't work properly

I have got a productImageArray that contains url as elements of the array.
I'm trying to load those urls in my image view.
Following is the way as of how I'm loading it.
UIActivityIndicatorView *spinner=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
spinner.center=CGPointMake(160.0,240.0 );
spinner.hidesWhenStopped=YES;
[self.view addSubview:spinner];
[spinner startAnimating];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
dispatch_async(queue, ^{
NSData *storeImageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:productImageArray[indexPath.row]]];
self.productImage.image = [UIImage imageWithData:storeImageData];
dispatch_sync(dispatch_get_main_queue(), ^{
[spinner stopAnimating];
});
});
The problem is that,
Only the last cell of my tableview loads the image whereas the remaining cell does not load the image from the url
Is there any other better way of loading the image from url directly into my UIImage using native methods?
When I use the following code, each cell of my tableview loads the image data but still it freezes the User interface till the data is loaded completely
NSData *storeImageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:productImageArray[indexPath.row]]];
self.productImage.image = [UIImage imageWithData:storeImageData];
#Anbu.Karthik answer is right.
But, maybe the simplest solution is to use something like SDWebImage no? This library will handle this issue and much more (cache, error management, proper tableview cells handling, ...).
I think you should, at least, take a few minutes to look at it: https://github.com/rs/SDWebImage
Edit:
If you use SDWebImage, and UIActivityIndicator-for-SDWebImage, you can replace your entire code by this:
[self.productImage setImageWithURL:[NSURL URLWithString:productImageArray[indexPath.row]]
usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
More informations on UIActivityIndicator-for-SDWebImage: https://github.com/JJSaccolo/UIActivityIndicator-for-SDWebImage
try this
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
dispatch_async(queue, ^{
NSData *storeImageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:productImageArray[indexPath.row]]];
dispatch_sync(dispatch_get_main_queue(), ^{
[spinner stopAnimating];
self.productImage.image = [UIImage imageWithData:storeImageData];
});
});
or try like
self.productImage.image = nil; //// [UIImage imageNamed:#"default.png"];
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:productImageArray[indexPath.row]] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (data) {
UIImage *currentImage = [UIImage imageWithData:data];
if (currentImage) {
dispatch_async(dispatch_get_main_queue(), ^{
UITableviewCell *getCurrentCell = (id)[tableView cellForRowAtIndexPath:indexPath];
if (getCurrentCell)
self.productImage.image = currentImage;
});
}
}
}];
[task resume];
NSString *url_Img1 = #"Your url";
Uiimageview *view_Image.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url_Img1]]];

UITableViewCell placeholder image

I'm working with AFNetworking to load my images for cell placeholder. Here is my code example. (Token from here)
NSURL *url = [NSURL URLWithString:daysWeather.weatherIconURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
UIImage *placeholderImage = [UIImage imageNamed:#"placeholder"];
__weak UITableViewCell *weakCell = cell;
[cell.imageView setImageWithURLRequest:request
placeholderImage:placeholderImage
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
NSLog(#"Load placeholder img");
weakCell.imageView.image = image;
[weakCell setNeedsLayout];
} failure:nil];
return cell;
And now I have a question. Does this images load every time, when it becomes visible? As you can see I've added NSLog(#"Load placeholder img"); in success block. And I see, that this code calls every time, when cell becomes visible (after it was visible, disappeared and become visible again)
Yes success block called every time. But AFNetworking will download the image only once and saved it in cache. Once you make request again for same URL or image it will directly load image from cache if available.
Also, if you don't want to do any specific operation in block, then simply use setImageWithURL:placeholderImage.

Load UIImage from URL in iOS

I am trying to load a UIImage from its URL with completionand placeholder image , but neither the UIImage nor the placeholder UIImage are loaded.
Here is my code:
NSURL *url = [NSURL URLWithString:#"http://assets.gearlive.com/tvenvy/blogimages/stewiegriffin.jpg"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.imageView setImageWithURLRequest:request placeholderImage:[UIImage imageNamed:#"bg.png"]
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
imageView.image = image;
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {}
];
Try this code to get image...
Code:
NSURL *url = [NSURL URLWithString:#"http://www.fnordware.com/superpng/pnggrad16rgb.png"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
[self.imageview1 setImage:image];
Note: i have used test url. you can use your url.
Update :
Swift 3.0 Code :
let url = URL(string: "http://www.fnordware.com/superpng/pnggrad16rgb.png")
do {
let data = try Data(contentsOf: url!)
var image = UIImage(data: data)
self.imageView.image = image
print(image)
} catch {
}
Note : In Xcode version 7.1 and above you need to set ATS (App Transport Security). To set ATS you need write below code in info.plist file.
Make sure url of image should not be nil.
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
Use AFnetworking where you can set placeholder image also if the url is not correct. This is more efficient when you are loading images in a tableview or a collection view.
Import UIImageView+AFNetworking.h
#import "UIImageView+AFNetworking.h"
and us the following code:
NSString *url1=#"http://www.fnordware.com/superpng/pnggrad16rgb.png";
[self.image setImageWithURL:[NSURL URLWithString:url1] placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
You can download it from gitHub
Check out AsyncImageView. Its the best async image loader AFAIK. all you have to do is set the image URL to the imageview and the rest is taken care of. including caching.
I found the problem
My code is working correctly.
The problem was somewhere in my code , the ImageView was nil.
Thanks all

UIImageView+Afnetworking doesn't Work Properly

I Have copied the contents of file from here and created a UIImageView+AFNetworking.h and imported in my implementation file
Now When I Write the following code i get this error but when i remove the block of code then everything works fine.
I want to display image in a custom table cell.The url of image i am grabbing Through JSON
NSURLRequest *imageRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:[dictArray objectForKey:#"image"]]];
[cell.thumbnailImageView setImageWithURLRequest:imageRequest placeholderImage:nil
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image){
NSLog(#"success");
cell.thumbnailImageView.image = image;
cell.thumbnailImageView.contentMode = UIViewContentModeScaleAspectFit;
cell.thumbnailImageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[cell setNeedsLayout];// To update the cell {if not using this, your image is not showing over cell.}
}failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){
NSLog(#"Failure");}];
Here is the screen shot of the error
It Crashes after loading
Instead of using afnetworking You can just use dispatch method
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSString *url = [indexDic objectForKey:#"image"];
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
UIImage *image = [UIImage imageWithData:imageData];
dispatch_async(dispatch_get_main_queue(), ^{
cellImg.image = image;
});
});
return cell;
}

iOS set/change background image on load

I have to make som changes to a iPhone app...
How can i change the background on a UIViewController on load (viewDidLoad) .. I have to show a .png from a URL .. Is that posible?
I have tried:
NSURL *url = [NSURL URLWithString:#"http://url_to_my_project/xmas-bg-test.png"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
self.view.backgroundColor = [UIColor colorWithPatternImage:image];
this is from my : "- (void)viewDidLoad" method .. Nothing happend when I start my app.. no errors ether.
I have also tried from my .. viewDidAppear
You have to create UIImageView as a background image. Remove self.view.backgroundColor = ... line and add this:
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = self.view.frame;
[self.view addSubview:imageView];
[self.view sendSubviewToBack:imageView];
in viewDidLoad: method.
That's not how you add a background to a view controller. Add a new UIImageView ivar to your view controller subclass and use that.
- (void)viewDidLoad {
...
imageView.image = [UIImage imageWithData:data];
}
You have to make sure you create this image view properly. Either by adding an image view in Interface Builder and linking it to your imageView ivar, or by creating it yourself in awakeFromNib or loadView.
The other answers are correct for saying that you should be using an image view to display the image. However, you should consider making a request for the image. This way, if the request fails you can handle it by displaying a different image or what ever you want. Here's a rough example.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://url_to_my_project/xmas-bg-test.png"] cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:5.0];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (response && !error) {
UIImage *image = [UIImage imageWithData:data];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
[imageView setImage:image];
[self.view addSubview:imageView];
}
}];

Resources