Search code examples
iphoneiosuibuttonreloadmultitasking

How to reload image in UIButton in applicationDidBecomeActive


I have a MenuViewController that loads when the app loads up; it is the root view of a UINavigationController.

Within the view I have a UIButton with an image that loads from a URL, as well as a label (its a picture indicating the weather and the current temp.).

Everything works fine, but if I am using the app on an iPhone 4, with multi-tasking, when the home button is pressed and then the app is reopened, I need the UIButton image and temp. label to reload.

I have tried calling this in my AppDelegate under applicationDidBecomeActive:

[self parseWeatherXML]; //re-parse weather data
[menuViewController reloadWeatherData]; //loads the image/label from the XML

with no luck.

I have also tried releasing menuViewController in applicationWillResign, then reallocating menuViewController in applicationDidBecomeActive so the viewDidLoad method gets called again, both ways just end up crashing my app.

Any help appreciated!

EDIT Heres my method that gets called with the notification:

- (void)reloadWeather
{
[self parseWeatherXML];
UIImage *img = [UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString:iconURL]]];
if (img != nil) 
{ 
    NSLog(@"setting image");
    [weatherButton setImage:img forState:normal];
    img = nil; 
}
currentTemp = [currentTemp stringByAppendingString:@"°F"];
[tempLabel setText:currentTemp];
tempLabel.adjustsFontSizeToFitWidth = YES;
if([self isIPad])
{
    tempLabel.textAlignment = UITextAlignmentRight;
    [tempLabel setFont: [UIFont systemFontOfSize: 45.0]];
}

currentTemp = nil;
}

Solution

  • I would have your MenuViewController become an observer to the UIApplicationDidBecomeActiveNotification and perform the parseWeatherXML data. I would think you would be refreshing the data from the URL, so you would need to wait for that data to come back again. So, I would follow the same logic that you are doing when you receive that notification.

    UIApplicationDidBecomeActiveNotification

    Posted when the application becomes active. An application is active when it is receiving events. An active application can be said to have focus. It gains focus after being launched, loses focus when an overlay window pops up or when the device is locked, and gains focus when the device is unlocked.

    Availability

    Available in iOS 2.0 and later.

    Declared In

    UIApplication.h