简体   繁体   中英

Dictionary initialized in AppDelegate has nil value in UIViewController

I am using open weather API to get live weather data and displaying it in a UIViewController. However I make the http request in AppDelegate. So I made the API request in AppDelegate in a method called weatherForcast(), converted the JSON response to a NSDictionary object, and printed the object to the console just to make sure everything worked fine, and it did.

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);
}

The dictionary is perfect.

Then in the UIViewController in viewDidLoad I call the method weatherForecast() and then call a method UpdateTemperature() which sets all the texts of the labels to data in the dictionary. Here is the code in the method 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;
}

All the labels will only be set if the dictionary has at least one object within it, which it should. But it turned not not too. So I printed the dictionary, and got nil.

In AppDelegate when I printed the dictionary it was fine, but than in viewDidLoad when I printed the same dictionary it turned out to be nil. What is happening?

It's likely that when viewDidLoad gets called, weatherInfo has not been initialized yet. If it requires an http call the data may have not returned yet and therefore when you access it in viewDidLoad there is no object to access. You might want to try reconfiguring where you make your http request and create weatherInfo.

when you create object of appdelegate then all variable of appdelegate is reinitialized so it return nil. Just put your code into a fuction and simply return a dictionary

plz try this,

-(NSDictionary *) getWeatherInfo
{

    NSString *urllink = [NSString stringWithFormat:@"http://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&appid=%@&units=metric", 10.0, 10.0, @"api"];
    NSURL *jsonURL = [NSURL URLWithString:[self urlEncodeValue:urllink]];

    NSData *jsonData = [NSData dataWithContentsOfURL:jsonURL];
    NSLog(@"This is jsonURL:%@", jsonURL);
    NSError *err = nil;

    NSDictionary *weather_info=[NSDictionary dictionary];
    if(jsonData == nil)
    {
        NSLog(@"Error laoding jsonData");

    }
    else
    {
       weather_info = [NSJSONSerialization JSONObjectWithData: jsonData options: NSJSONReadingMutableContainers error: &err];
        NSLog(@"This is weatherInfo dictionary:%@", weather_info);


    }
    return weather_info;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM