I have an NSURLSession
that looks like this, and what I want to do, is if no data is returned then I want it to try again and again, for up to lets say 8 seconds or 3 attempts and then if still nothing is there, I will have it return no data. Here is what I have now,
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:urlIn] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// handle response
//use my data
// if no data I want to try again?
}] resume];
So I want it to either try 3 times or until 8 seconds has passed. How could I go about doing this,
Thanks for the help in advance.
Okay so I am almost there I just have a little bit more to work out with timer. Here is what I have.
I got properties
NSInteger attemptInt;
NSInteger _counter;
NSDate *date = [NSDate date];
And then these two methods for my timer
- (void)startCountdown
{
_counter = 8;
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(countdownTimer:)
userInfo:nil
repeats:YES];
}
- (void)countdownTimer:(NSTimer *)timer
{
_counter--;
if (_counter <= 0) {
[timer invalidate];
NSLog(@"8 sec passed");
}
}
And then here is where I am getting my data.
- (void)getMenuItems:(NSString*)urlIn{
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:urlIn] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//One problem I am facing is I have to call timer for main thread
if ([date timeIntervalSinceNow] <= 8 && [response expectedContentLength] == 0) {
attemptInt++;
[self getMenuItems:url];
}
if (attemptInt >= 3) {
NSLog(@"NO DATA");
}
else if ([response expectedContentLength] == 0) {
NSLog(@"TRY AGAIN");
attemptInt++;
[self getMenuItems:url];
}
else {
//GOT MY DATA :)
self.mealdata=[[MealData alloc]init:data];
}
So I got the attempts worked out am a timer set up I just need some help finishing up to check whether 8 seconds has passed first?