Ios NSURLSession-在后台下载一个小PNG图像
你能帮帮我吗。我想通过利用Ios NSURLSession-在后台下载一个小PNG图像,ios,objective-c,iphone,xcode,nsurlsession,Ios,Objective C,Iphone,Xcode,Nsurlsession,你能帮帮我吗。我想通过利用NSURLSession来改进这段代码?如何更改此代码以使用此构造 代码的目标是在背景中加载一个小的.png图像 NSDate *myDate = (NSDate *)[[NSUserDefaults standardUserDefaults] objectForKey:@"LastUpdate"]; NSString *img=[NSString stringWithFormat:phpLinkgetUpdates, myDate]; NSURL *url = [N
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;
谢谢你的帮助 下载您可以使用的图像。它将下载图像并存储到本地缓存中 目标C:
#import <SDWebImage/UIImageView+WebCache.h>
...
[imageView sd_setImageWithURL:[NSURL URLWithString:IMAGE_URL
placeholderImage:[UIImage imageNamed:@"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];
关于如何使用NSUrlSession下载单个文件,有很多示例。试着先用谷歌搜索一下。图片会显示一个更新图标,它来了又走。缓存将是坏的。可以关闭sdwebimage缓存吗?也没有sdwebimage吗?请检查我的另一个更新答案。它可能对你有用。@Phil\u Austria你能给我们一个你的图片url吗?@Phil\u Austria签出我的更新答案。这会解决你的问题。很乐意帮助你。只是要求投票。我不喜欢在我的答案中看到负数。
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];