Phil_Austria
Phil_Austria

Reputation: 47

NSURLSession - Downloading a small PNG image in the background

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

Answers (1)

Nirmalsinh Rathod
Nirmalsinh Rathod

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

Related Questions