0

I have a code which is doing an request once the app is running. My problem is how can i make the request every 5 seconds?

The code:

NSDictionary* headers = @{@"X-Mashape-Authorization": @"Key"};
NSDictionary* parameters = @{};

UNIHTTPJsonResponse* response = [[UNIRest get:^(UNISimpleRequest* request) {
    [request setUrl:@"https://willjw-statsfc-competitions.p.mashape.com/live.json?key=free&competition=premier-league&timezone=Europe%2FLondon"];

    [request setHeaders:headers];
    [request setParameters:parameters];
}] asJson];


NSData* rawBody = [response rawBody];
results = [NSJSONSerialization JSONObjectWithData:rawBody options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@", results);


for (int i = 0; i <= results.count-1; i++)
{


    NSString *homeTeam = [[results valueForKey:@"homeshort"] objectAtIndex:i ];
    NSString *awayTeam = [[results valueForKey:@"awayshort"] objectAtIndex:i ];
    NSString *time = [[results valueForKey:@"statusshort"] objectAtIndex:i ];
    NSString *homeScore = [NSString stringWithFormat:@"%@", [[[results valueForKey:@"runningscore"] objectAtIndex:i ] objectAtIndex:0]];
    NSString *awayScore = [NSString stringWithFormat:@"%@", [[[results valueForKey:@"runningscore"] objectAtIndex:i ] objectAtIndex:1]];


    [arrayBarclay addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:homeTeam,@"hometeam", awayTeam,@"awayteam", time, @"time", homeScore, @"homescore", awayScore, @"awayscore", nil]];

}
user3258468
  • 354
  • 7
  • 18

1 Answers1

0

For the easiest way, I suggest you use a NSTimer. Wrap this code in a function and then call the function with a timer.

NSTimer* myTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(targetMethod:) userInfo:nil repeats:YES];

The call above will create and start a NSTimer approximately every 5 seconds and it will repeat forever. The target method is called targetMethod and should contain your REST code.

Be careful not to run into cross-threading problems and to invalidate (cancel) the timer when you do not need it anymore. For example, when the screen displaying this data is gone.

More information about the timer in the following threads:

Community
  • 1
  • 1
Legoless
  • 10,942
  • 7
  • 48
  • 68