Reputation: 47
Can you help me please. I would like to improve this code, possibly by utilizing NSURLSession
? How would I change this code to use this construct?
The objective of the code is to load a small .png
image in the background.
NSDate *myDate = (NSDate *)[[NSUserDefaults standardUserDefaults] objectForKey:@"LastUpdate"];
NSString *img=[NSString stringWithFormat:phpLinkgetUpdates, myDate];
NSURL *url = [NSURL URLWithString:[img stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
UIImage *tmpImage = [[UIImage alloc] initWithData:data];
imgUpdate.image = tmpImage;
Thanks for your help!
Upvotes: 3
Views: 617
Reputation: 5186
For downloading the image you can use SDWebImage. It will download image and stored into the local cache memory.
Objective C:
#import <SDWebImage/UIImageView+WebCache.h>
...
[imageView sd_setImageWithURL:[NSURL URLWithString:IMAGE_URL
placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
Swift:
import SDWebImage
imageView.sd_setImage(with: URL(string: IMAGE_URL), placeholderImage: UIImage(named: "placeholder.png"))
You use below code:
NSString *str = YOUR_IMAGE_URL;
NSString* encodedUrl = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:encodedUrl];
NSURLSessionDataTask *downloadTask = [[NSURLSession sharedSession]
dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
UIImage *image = [UIImage imageWithData:data];
}];
[downloadTask resume];
Upvotes: 2