Cache NSData(with UIImages) - objective-c

Currently, I'm working on the client for the website. I have tonne of images that I need to load to my TableView. Here is what I'm currectly doing:
NSDictionary *propertyItems = [self.items objectAtIndex:indexPath.row];
cell.fio.font = [UIFont boldSystemFontOfSize:17.0f];
if([propertyItems objectForKey:#"online"] == [NSNumber numberWithInt:1])
cell.fio.textColor = [UIColor colorWithRed:0.3 green:0.6 blue:0.3 alpha:1.0];
dispatch_queue_t downloadPhotosQueue = dispatch_queue_create("downloadPhotosQeue", NULL);
dispatch_async(downloadPhotosQueue, ^{
NSData *photosData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.example.com/%#", [propertyItems objectForKey:#"photo_trumb"]]]];
dispatch_async(dispatch_get_main_queue(), ^{
cell.pic.image = [UIImage imageWithData:photosData];
});
});
cell.fio.text = [propertyItems objectForKey:#"fio"];
I'm doing this in cellForRowAtIndexPath: method.
Everything is loading fast. But the problem is, when I'm scrolling my table down, and after again up, the images are reloading over and over again.
Question: Is there any way to easily cache my UIImages that I'm getting from the server? So if they are loaded once, they wouldn't reload over and over again, while I'm running the app. Maybe I'm doing something wrong?
Thanks in advance!

I strongly recommend AsyncImageView. I use it and it works like a charm. Just set the image url and it handles everything itself.
AsyncImageView *imageView = [[AsyncImageView alloc]init];
imageView.imageURL = [NSURL URLWithString:#"https://www.google.es/logos/classicplus.png"];
It caches the image in memory so it won't retrieve it from the server again. It will also release them when receiving a memory warning.

To load image from a website I use AFNetworking. It provides a class to load an image from an URL:
Start by adding #import "UIImageView+AFNetworking" to the top of a
controller or a view implementation file. This category adds methods
to UIImageView, like:
[imageView setImageWithURL:[NSURL URLWithString:#"…"]];

i recommend this library to accomplish what you want.
in cellForRowAtIndexPath:
[cell.imageView setImageWithURL:
[NSURL URLWithString:[NSString stringWithString:#"www.yourimagepath.path"]]
placeholderImage:[UIImage imageNamed:#"no_image.jpg"]];
the library will cache the image for you. you can also set the setHolder of the image, so it wont look like a blank image while the images are downloading.

The problem is here :
NSData *photosData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.example.com/%#", [propertyItems objectForKey:#"photo_trumb"]]]];
dataWithContentsOfURL
It launch a request to the Url everytime the function is called (everytime you scrolled).
You need to load all the picture before cellForRowAtIndexPath.
Like in ViewDidLoad.
You can just store them in an array and display your picture's array in cellForRowAtIndexPath.
If it's really fast to load like you say : jsut load picture Once in CellForRowAtIndexPath. Store them in a mutableArray. And check if the picture already exist .

Related

Image is not visible on Watch App programatically

I have a very weird issue. I have a watch app and I am trying to display an image programatically. When I debug the code, I can see the image is correctly loaded but on simulator or real device I cannot see the image. I have added that image in both watch and extension bundle resources.
Firstly I use the code below to open the view.
NSArray *objects =[NSArray arrayWithObjects:#"MainPageView",#"InterfaceController",#"PoseImageView",nil];
[self presentControllerWithNames:objects contexts:nil];
Inside PoseImageView I am trying to display an image with:
UIImage *imgTest = [UIImage imageNamed:[NSString stringWithFormat:#"1.jpg", strAngle]]; // I can see 1.jpg in debugger
[_imgPose setImage: imgTest];
The image is not there on watch or simulator. I am wondering how to fix the issue.
Note: From assets its not loading as well.
Note2: I can only display the image if the view is initial view.
You are trying to use imageNamed for .jpg which will not work.
Try using
NSString *filePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"imageName"] ofType:#"jpg"];
UIImage *theImage = [UIImage imageWithContentsOfFile:filePath];

how to load image from server (url) to uitableview in Xcode

I need to load image from server(url) to UITableView. So i tired below code, but no use.
UIImageView *img=[[UIImageView alloc]init];
img.frame=fr;
img.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:countimg]]];
[cell.contentView addSubview:img];
Here countimg is NSMutableArray. countimg contains url of all images to load. But its not working, because its not a string variable. I don't know how to change NSMutuableArray to String.
Anyone help me.
You can get string urls from countimg array like this,
[countimg objectAtIndex:index];
Where index is an integer of range between >=0 && < [countimg count]
Now if you're using countimg array in UITableView delegate then, you've replace index variable with indexPath.row.
So for now your code would look like this,
UIImageView *img=[[UIImageView alloc]init];
img.frame=fr;
img.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[countimg objectAtIndex:indexPath.row]]]]; //note this
[cell.contentView addSubview:img];
Update:
As #DavidAtkinson, suggestion, you should not use dataWithContentsOfURL method to load a NSURL to download a image. As its perform in main thread and will stuck the UI until download would not completes. Its better to load image in background.
Also, there's some asynchronous UIImageView's available, one which I am using is SDWebImage.
Use SDWebImage to load your image from server. here using this library you can put placeholder image in tableview cell's image view till the image loaded. You can even cache your image by just doing a single line code
[UIImageView setImageWithUrl:[pass your URL here] placeholderImage:[pass name of placeholder image] options:SDWebImageRefreshCached]
If you are trying to load your images from URL into a tableview,the SDWebImage code from Github does not specify how to do that.You have to create an object at index,then load the object for key name from the file you are parsing from.This will require you to change the SDWebImage code so that instead of parsing directly from a specific url,its parsing from
an object key name that contains an image url from your json or xml file.
Here is a sample code for loading an image from an object key in a json:
NSURL* url = [NSURL URLWithString:[dictionaryObject valueForKey:#"yourfile"]];
NSData *data = [NSData dataWithContentsOfURL:url];
dispatch_sync(dispatch_get_main_queue(), ^{
UIImageView *imgViewThumb=[[UIImageView alloc]initWithFrame:imgView.frame];
[imgViewThumb setImage:[UIImage imageWithData:data]];
[cell addSubview:imgViewThumb];

iOS use cached image with SDWebImage properly

I am using SDWebImage to get pictures.
let's say I have two view controllers A and B. B is the next view of A. they need to show the same image:
[iconIamgeView setImageWithURL:[NSURL URLWithString:#"http://www.example.com/icon.jpg"];
I thought SDWebImage would cache http://www.example.com/icon.jpg after this code in A, so B was going to use the cache. Thus there should not be a detectable latency when I used this code to show the same image in B. However, it seems that I was wrong. there was an obvious latency when I wanted to show this image in B.
How can I use the cache properly? thanks!
I am sorry that the problem I mentioned in the question was not the real problem.
[iconIamgeView setImageWithURL:[NSURL URLWithString:#"http://www.example.com/icon.jpg"];
this code does the cache work well.
the real problem is my code of setting image was not on the main thread, so I could not show the image immediately. I used dispatch_async to solve the problem:
dispatch_async(dispatch_get_main_queue(), ^{
[iconIamgeView setImageWithURL:[NSURLURLWithString:#"http://www.example.com/icon.jpg"];
});
hope this answer may help someone who faces the same issue.
NSURL *imageURL = [NSURL URLWithString:[linkImageArray objectAtIndex:index]];
UIImage *placeholderImage = [UIImage imageNamed : [linkImageArray objectAtIndex: index]];
[imageView setImageWithURL:imageURL
placeholderImage:placeholderImage
options:SDWebImageRefreshCached
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType)
{
NSLog(#"image loaded");
}];

How To Load Images From NSHomeDirectory

So, I'm currently saving images in my UIImageView via this method:
- (void)applicationDidEnterBackground:(UIApplication*)application {
NSString *image1 = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/image1.png"];
NSString *image2 = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/image2.png"];
}
The images save just fine, but I have no idea how to set the UIImageViews images in viewDidLoad. This is what I've been trying:
- (void)viewDidLoad
{
self.imageView.image =[UIImage imageNamed:[(NSHomeDirectory *)Documents objectForKey:#"image1"]];
self.imageView2.image =[UIImage imageNamed:[(NSHomeDirectory *)Documents objectForKey:#"image1"]];
}
But, obviously that is not working. I'm having trouble understanding the basics here. Any help would be great, thanks!
The -imageNamed: method looks in the application's main bundle if the named image hasn't been cached yet. From the docs:
The name of the file. If this is the first time the image is being loaded, the method looks for an image with the specified name in the application’s main bundle.
(See UIImage class reference)
You want -imageWithContentsOfFile: instead.

To Convert HTML doc to image in cocoa

is it possible to convert the HTML page to image in cocoa?
Actually i have created the complete view in the HTML and now i want to convert the whole html preview to the image (any jpeg or png etc.).
I couldn't find any resource or sample on the web, which provides some sort of help on my above queries.It's highly appreciated if someone could share his wisdom on how I can achieve this.
Thanks in advance..
First off, I'd like to thank sergio... his answer got me started but I thought I'd share some of the code that I didn't find obvious that I had to write to make it work:
Here's how to make a thumbnail for a page without ever having it displayed:
// Your width and height can be whatever you like, but if you want this to render
// off screen, you need an x and y bigger than the superview's width and height
UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectMake(largerScreenDimension, largerScreenDimension, largerScreenDimension, largerScreenDimension)];
[self.view addSubview:webView]; // UIWebViews without an assigned superview don't load ever.
webView.delegate = self; // or whoever you have implement UIWebViewDelegate
webView.scalesToFit = YES; // This zooms the page appropriately to fill the entire thumbnail.
[webView loadRequest:[NSURLRequest requestWithURL:url]];
Then implement this in your delegate:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
UIGraphicsBeginImageContext(webView.bounds.size);
[webView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *webViewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *thumbnailData = UIImagePNGRepresentation(webViewImage);
[webView removeFromSuperview];
}
Finally, to display this thumbnail you'll need something like:
thumbnailImageView.image = [UIImage imageWithData:thumbnailData];
As a bonus thing I'll mention, I wanted multiple thumbnails to be generated at once. I found using objc_setAssociatedObject() and objc_getAssociatedObject() to be very helpful with keeping track of which webView was loading which thumbnail. Going into detail on how that worked is beyond the scope of this question, though.
You can draw your view in an image context, like this:
UIWebView* view = ...
....
UIGraphicsBeginImageContext(view.bounds.size);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imagedata = UIImagePNGRepresentation(viewimage);
NSString *encodedString = [imageData base64Encoding];
Another option would be using Quartz PDF engine to create a PDF.