从 URL 延迟获取图像

Get image from URL delay

我正在尝试在我的横幅中加载图像以及该横幅的 URL 并且一切都很好,除了它在几秒钟后出现(10+ 秒)

首先我认为这可能是连接速度问题,但如果我硬编码图像需要显示的行,它会立即显示。

这是我现在正在做的事情。

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:adUrl completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    adJson = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    adImageURL = [NSString stringWithFormat:@"%@", adJson[@"sponsor"][@"sponsor_image"]];
    adUrlString = [NSString stringWithFormat:@"%@", adJson[@"sponsor"][@"sponsor_url"]];

    [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;

    // Set adImage
    [[self adBanner]setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:adImageURL]]]];

    // Ad TapGuestures to adImage
    UITapGestureRecognizer *adTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(adTapMethod)];
    [[self adBanner]setUserInteractionEnabled:YES];
    [[self adBanner]addGestureRecognizer:adTap];
}];
[dataTask resume];

如我所说,如果我这样做:

[[self adBanner]setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"example.com/img.png"]]]];

然后将该代码从 NSURLSessionDataTask 中取出,它立即出现。

我做错了什么以及如何让图像尽快出现?

唯一的延迟来自连接,然后是设备更新其显示。请记住,使用 dataWithContentsOfURL 的直接调用会强制主队列在执行任何操作之前等待图像。如果你用 NSURLSession 执行它,它自然会花费更长的时间,因为它没有被设置为高优先级。

您应该这样包括 setImage:

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:adUrl completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    adJson = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    adImageURL = [NSString stringWithFormat:@"%@", adJson[@"sponsor"][@"sponsor_image"]];
    adUrlString = [NSString stringWithFormat:@"%@", adJson[@"sponsor"][@"sponsor_url"]];

    [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;

    // Set adImage
    dispatch_async(dispatch_get_main_queue(), ^{
        [[self adBanner] setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:adImageURL]]]];

        // Ad TapGuestures to adImage
        UITapGestureRecognizer *adTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(adTapMethod)];
        [[self adBanner] setUserInteractionEnabled:YES];
        [[self adBanner] addGestureRecognizer:adTap];
    });
}];
[dataTask resume];