2014-02-23 15 views
0

我有一个代码,一旦应用程序正在运行请求。我的问题是我如何每5秒发出一次请求?有史以来5秒的安静请求

代码:

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]]; 

} 

回答

0

对于最简单的方法,我建议你使用一个NSTimer。将此代码包装在一个函数中,然后用计时器调用函数。

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

上面的调用大约每5秒创建一个NSTimer并且它会一直重复。目标方法被称为targetMethod并应包含您的REST代码。

小心不要碰到交叉线程问题,并在您不再需要时使计时器无效(取消)。例如,当显示此数据的屏幕消失时。

大约在以下线程定时器的更多信息: