2013-06-20 47 views
0

我正在使用我的当前位置的天气api,使用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"]; 

任何方式重定向或通过提供城市附近找到。可任何一个请帮助我吗?

回答

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,从而使会会simpleforecastarrofforecastday)。你真的应该测试这些是否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 
} 
+0

也想指出的是,OP取得了同步网络通话。 – 0x8badf00d

+1

同意(当然,假设他正在从主队列中调用geoCodeUsingAddress)。他真的应该使用GCD'dispatch_async'或者创建一个操作队列,然后调用'addOperationWithBlock',将这段代码调度到后台队列中。或者他应该执行'sendAsynchronousRequest'或使用'NSURLConnection'委托方法。 – Rob