从URL延迟中获取图像

时间:2015-08-06 16:35:22

标签: ios objective-c nsurlsession ios7.1

我正在尝试在我的横幅中加载图片以及该横幅的网址,一切都很好,除了在几秒钟(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中删除,它不会在第二个时间内出现。

我做错了什么以及如何尽可能快地获得图像?

1 个答案:

答案 0 :(得分:1)

唯一的延迟是来自连接&然后从设备更新它的显示。请记住,使用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];