Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Theclamshell

macrumors 68030
Original poster
Mar 2, 2009
2,741
3
I am working on something that will take data from a website every time the counter counts down. The issue is that I want the counter to stop when the user leaves the view and not keep retrieving data. I have been trying to add this in,
Code:
[timername invalidate];
to no avail. Can someone tell me what I need to do so the timer stops when the view is left and re-starts from new when someone goes back to the view?

Thanks.

Code:
#import "Price.h"

@interface Price ()
@property (strong, nonatomic) IBOutlet UILabel *priceLabel;
@property (strong, nonatomic) IBOutlet UILabel *countdownLabel;


@end

@implementation Price
int counter;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    counter = 10;
    
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:(self) selector:@selector(countdown) userInfo:nil repeats:YES];
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)getPrice{
    NSURL *url = [NSURL URLWithString:@"myURL"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         if (error ==nil){
             NSDictionary *spotPrice = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]
             ;
             self.priceLabel.text = [[[spotPrice objectForKey:@"amount"] stringByAppendingString:@" "]stringByAppendingString:[spotPrice objectForKey:@"currency"]];
         }
         
     }];
}

-(void)countdown{
    counter--;
    self.countdownLabel.text = [NSString stringWithFormat:@"%d", counter];
    if (counter == 0){
        counter = 15;
        [self getPrice];
    }
 
Last edited:

Paulie87

macrumors newbie
Mar 2, 2014
24
0
Use viewWillDisappear: method to stop the timer, and then viewWillAppear: method to restart the timer :)
 

Theclamshell

macrumors 68030
Original poster
Mar 2, 2009
2,741
3
Thank You. Those worked fine for me. I actually also found a flaw in my counter which I fixed and it fulfills it's purpose much better now. Thank you.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.