2014-02-23 48 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代碼。

小心不要碰到交叉線程問題,並在您不再需要時使計時器無效(取消)。例如,當顯示此數據的屏幕消失時。

大約在以下線程定時器的更多信息: