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,
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:
[timername invalidate];
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: