0

wundergroundを使用して、現在の場所に Weather 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したがって , になります)。これらのいずれかが該当するかどうかを実際にテストし、その状況を適切に処理する必要があります。たとえば、これらのうちの 1 つまたは複数がそうではない、またはそのループ内に正常に到達したと想定する、後のコードがあると思われます。simpleforecastarrofforecastdaynilnilfor

さらに良いことに (つまり、上記の点に加えて)、サーバーから報告されたエラーをテストする必要があります。次のように言う必要があります。

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 に答える