Reputation: 1748
I am trying to load image in my banner as well as URL for that banner and everything is just fine except it apears after a few seconds (10+ sec)
First I was thinking that it may be connection speed but if I hardcoded the line where image needs to apear it apears immediatly.
Here is what I am doing right now.
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];
As I said, if I do:
[[self adBanner]setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"example.com/img.png"]]]];
and put that code out of NSURLSessionDataTask it apears in no second.
What am I doing wrong and how to get image apear as fast as possible?
Upvotes: 0
Views: 418
Reputation: 5990
The only delays would be from connection & then from the device updating it's display. Remember that the direct call with dataWithContentsOfURL
forces the main queue to wait on the image before doing anything. If you execute it with a NSURLSession
it would naturally take a bit longer since it isn't set as a high priority.
You should include setImage:
as such.
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];
Upvotes: 1