我正在调用 API 来获取一些实时信息。当没有实时信息时会返回:
error =“未找到现场比赛”;
否则会返回不同的信息,如
hometeam
、awayteam
、score
等。
在我的循环中,我将这些信息添加到数组中
arrayEuropa
。问题是,如果 API 请求返回错误消息,它不应该向 arrayEuropa
添加任何内容。
如何获得这个?
我尝试了不同的方法,这些方法在返回错误消息时有效,但在没有错误消息时崩溃。
这是我的代码:
NSDictionary* headers4 = @{@"X-Mashape-Authorization": @"key"};
NSDictionary* parameters4 = @{};
UNIHTTPJsonResponse* response4 = [[UNIRest get:^(UNISimpleRequest* request4) {
[request4 setUrl:@"https://willjw-statsfc-competitions.p.mashape.com/live.json?key=APIKEY&competition=europa-league&timezone=Europe%2FLondon"];
[request4 setHeaders:headers4];
[request4 setParameters:parameters4];
}] asJson];
NSData* rawBody4 = [response4 rawBody];
results4 = [NSJSONSerialization JSONObjectWithData:rawBody4 options:NSJSONReadingMutableContainers error:nil];
for (int i = 0; i <= results4.count-1; i++)
{
NSString *homeTeam = [[results4 valueForKey:@"homeshort"] objectAtIndex:i ];
NSString *awayTeam = [[results4 valueForKey:@"awayshort"] objectAtIndex:i ];
NSString *time = [[results4 valueForKey:@"statusshort"] objectAtIndex:i ];
NSString *homeScore = [NSString stringWithFormat:@"%@", [[[results4 valueForKey:@"runningscore"] objectAtIndex:i ] objectAtIndex:0]];
NSString *awayScore = [NSString stringWithFormat:@"%@", [[[results4 valueForKey:@"runningscore"] objectAtIndex:i ] objectAtIndex:1]];
[arrayEuropa addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:homeTeam,@"hometeam", awayTeam,@"awayteam", time, @"time", homeScore, @"homescore", awayScore, @"awayscore", nil]];
}
也许添加存储的json,这样会更容易提供帮助..
但是你可能应该做的是首先检查是否有值让我们说:
if([[results4 valueForKey:@"homeshort"] objectAtIndex:i ])
在存储之前。或者更好的是你可以检查错误:
if([[results4 valueForKey:@"error"] isEqualToString: ""No live games found" ])
{ return; }
然后返回。
希望这有帮助