Open Weather API を使用してライブ気象データを取得し、UIViewController に表示しています。ただし、AppDelegate で http 要求を行います。そこで、weatherForcast() というメソッドで AppDelegate の API 要求を作成し、JSON 応答を NSDictionary オブジェクトに変換し、オブジェクトをコンソールに出力して、すべてが正常に機能したことを確認しました。
NSString *urllink = [NSString stringWithFormat:@"http://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&appid=%@&units=metric", lat, lng, WEATHERAPIKEY];
NSURL *jsonURL = [NSURL URLWithString:[self urlEncodeValue:urllink]];
NSString *jsonDataString = [[NSString alloc]initWithContentsOfURL:jsonURL];
NSData *jsonData = [jsonDataString dataUsingEncoding:NSUTF16StringEncoding];
NSLog(@"This is jsonURL:%@", jsonURL);
NSError *err = nil;
if(jsonData == nil)
{
NSLog(@"Error laoding jsonData");
}
else
{
self.weatherInfo = [NSJSONSerialization JSONObjectWithData: jsonData options: NSJSONReadingMutableContainers error: &err];
NSLog(@"This is weatherInfo dictionary:%@", self.weatherInfo);
}
辞書は完璧です。
次に、viewDidLoad の UIViewController で、weatherForecast() メソッドを呼び出し、UpdateTemperature() メソッドを呼び出して、ラベルのすべてのテキストを辞書のデータに設定します。UpdateTemperature メソッドのコードは次のとおりです。
NSLog(@"This is the weatherInfo dictionary: %@", appDel.weatherInfo);
if([appDel.weatherInfo count] > 0 && appDel.isNetworkAvailable)
{
NSLog(@"Went into weatherInfo.count > 0");
lblCondition.text = [NSString stringWithFormat:@"condition:%@", [[[appDel.weatherInfo valueForKey:@"weather"] objectAtIndex:0] valueForKey:@"description"]];
lblHumidity.text = [NSString stringWithFormat:@"humidity:%@", [[appDel.weatherInfo valueForKey:@"main"] valueForKey:@"humidity"]];
lblTemperature.text = [NSString stringWithFormat:@"%@ Celsius", [[appDel.weatherInfo valueForKey:@"main"] valueForKey:@"temp"]];
imgWeather.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", WEATHERCONDITIONIMGURL, [appDel.weatherInfo valueForKey:@"icon"]]]]];
lblDegree.hidden = FALSE;
[getTemp stopAnimating];
}
else
{
lblDegree.hidden = TRUE;
}
すべてのラベルは、ディクショナリに少なくとも 1 つのオブジェクトが含まれている場合にのみ設定されます。しかし、そうではありませんでした。だから私は辞書を印刷し、nilを得ました。
辞書を印刷したときのAppDelegateでは問題ありませんでしたが、同じ辞書を印刷したときのviewDidLoadよりもnilでした。何が起こっている?