Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/security/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios NSURLSession-在后台下载一个小PNG图像_Ios_Objective C_Iphone_Xcode_Nsurlsession - Fatal编程技术网

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