NSURLSession - 在后台下载一个小的 PNG 图像



你能帮帮我吗?我想改进这段代码,可能通过使用NSURLSession?我将如何更改此代码以使用此构造?

代码的目的是在背景中加载一个小.png图像。

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;

感谢您的帮助!

要下载映像,您可以使用SDWebImage。它将下载图像并存储到本地缓存中。

目标C:

#import <SDWebImage/UIImageView+WebCache.h>
...
[imageView sd_setImageWithURL:[NSURL URLWithString:IMAGE_URL
placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

迅速:

import SDWebImage
imageView.sd_setImage(with: URL(string: IMAGE_URL), placeholderImage: UIImage(named: "placeholder.png"))

使用以下代码:

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];

最新更新