0

我正在使用wunderground将天气 api 用于我当前的位置。当当前位置城市在 API 中不可用时,应用程序会崩溃。现在我想在当前位置城市不可用时重定向附近的天气位置城市。

这是我的代码,

 -(void) geoCodeUsingAddress:(NSString *)address
 {
    NSString       *esc_addr = [address stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    NSString *urlString =[NSString stringWithFormat:@"http://api.wunderground.com/api/8e2edc55aaf7cfa7/geolookup/conditions/forecast/q/%@.json",esc_addr];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    NSData *response1 = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSDictionary *alldicdata=[NSJSONSerialization JSONObjectWithData:response1 options:0 error:nil];
    NSDictionary *forecast=[alldicdata objectForKey:@"forecast"];
    NSDictionary *simpleforecast=[forecast objectForKey:@"simpleforecast"];
    NSArray *arrofforecastday=[simpleforecast objectForKey:@"forecastday"];
    NSMutableArray *dataStore1=[[NSMutableArray alloc]init];
    for(NSDictionary *dict in arrofforecastday)
    {
    NSMutableDictionary *data=[[NSMutableDictionary alloc] init];
    [data setObject:[dict objectForKey:@"conditions"] forKey:@"conditions"];

有任何方法可以重定向或找到附近的城市。有人可以帮我吗?

4

1 回答 1

0

看一个错误响应:

{
    "response": {
        "version": "0.1",
        "termsofService": "http://www.wunderground.com/weather/api/d/terms.html",
        "features": {
            "geolookup": 1,
            "conditions": 1,
            "forecast": 1
        },
        "error": {
            "type": "querynotfound",
            "description": "No cities match your search query"
        }
    }
}

我实际上看不到您与我们共享的代码片段会如何崩溃(因为出错时,forecast只会是nil,因此也会是simpleforecast, arrofforecastday)。您真的应该测试其中是否有任何一个,nil并优雅地处理这种情况。我怀疑你有一些后来的代码假设,例如,其中一个或多个不是nil,或者你成功地进入了那个for循环。

更好的是(即除了以上几点),您应该测试服务器报告的错误,您应该说:

NSDictionary *response = [alldicdata objectForKey:@"response"];
NSDictionary *errorDictionary = [response objectForKey:@"error"];
NSDictionary *errorType = [errorDictionary objectForKey:@"type"];
NSDictionary *errorDescription = [errorDictionary objectForKey:@"description"];

if (errorType != nil)
{
    // handle the error here
}
于 2013-06-20T12:19:51.557 回答