I want to enable Timer only when user is logged in. How to go about this? I tried but getting session time out message even when user is on login screen.
#import "TIMERUIApplication.h"
#implementation TIMERUIApplication
//here we are listening for any touch. If the screen receives touch, the timer is reset
-(void)sendEvent:(UIEvent *)event
{
[super sendEvent:event];
if (!myidleTimer)
{
[self resetIdleTimer];
}
NSSet *allTouches = [event allTouches];
if ([allTouches count] > 0)
{
UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase;
if (phase == UITouchPhaseBegan)
{
[self resetIdleTimer];
}
}
}
-(void)resetIdleTimer
{
if (myidleTimer)
{
[myidleTimer invalidate];
}
//convert the wait period into minutes rather than seconds
int timeout = kApplicationTimeoutInMinutes * 60;
myidleTimer = [NSTimer scheduledTimerWithTimeInterval:timeout target:self
selector:#selector(idleTimerExceeded) userInfo:nil repeats:NO];
}
//if the timer reaches the limit as defined in kApplicationTimeoutInMinutes, post this notification
-(void)idleTimerExceeded {
[[NSNotificationCenter defaultCenter]
postNotificationName:kApplicationDidTimeoutNotification object:nil];
}
and
-(void)applicationDidTimeout:(NSNotification *) notif {
NSLog (#"time exceeded!!");
UIViewController *controller = [[UIStoryboard
storyboardWithName:#"MainStoryboard" bundle:NULL]
instantiateViewControllerWithIdentifier:#"mainView"];
//I've tried a few varieties of the if statement to no avail. Always goes to else.
if ([controller isViewLoaded]) {
NSLog(#"Already there!");
}
else {
NSLog(#"go home");
[(UINavigationController *)self.window.rootViewController pushViewController:controller animated:YES];
//[(TIMERUIApplication *)[UIApplication sharedApplication] resetIdleTimer];
}
}
Related
When I use [self performSelector:#selector(checkFirstSynchro) withObject:nil afterDelay:30.0]; in the checkFirstSynchro function, it seems not to work. Is it because it is in a Class function?
-(void) viewDidLoad
{
...
[self checkFirstSynchro]
...
}
- (void) checkFirstSynchro
{
//Check if firstSynchro
BOOL firstSynchro = [[[NSUserDefaults standardUserDefaults] valueForKey:#"FirstSynchro"] boolValue];
if (!firstSynchro)
{
[Reachability checkInternetConnectivityWithSuccessCompletion:^(NSError *error) //test if there is internet c
onnection
{
if (error == nil)
{
[self sync:connectBtn];
}
else
{
[self performSelector:#selector(checkFirstSynchro) withObject:nil afterDelay:30.0];
}
}];
}
}
It launches well the function, but it doesn't execute the perform 30.0 seconds later.
I tried this instead of the performSelector, but without success:
[NSTimer scheduledTimerWithTimeInterval:TIMER_FIRST_SYNCHRO
target:self
selector:#selector(checkFirstSynchro)
userInfo:nil
repeats:NO];
It launches well the function, but it doesn't execute the [NSTimer scheduledTimerWithTimeInterval 30.0 seconds later.
Thanks in advance.
I had implemented a simple countdown with UIDatePicker and NSTimeInterval and it works correctly, but I have the following problem: when I run the app in the Xcode simulator, if I press Ctrl + shift + h, the countdown works in background, but when I run the app on my iPhone 6 and if I press the home button, the countdown stops and it doesn´t work in background.
I have implemented the following notification (AppDelegate.m):
- (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
[[NSNotificationCenter defaultCenter] postNotificationName:#"didEnterBackground" object:nil];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
[[NSNotificationCenter defaultCenter] postNotificationName:#"didEnterForeground" object:nil];
}
The code in ViewController.m is:
- (void)viewDidLoad {
self.mensajeCuenta.hidden = YES;
self.botonDetenerCuenta.hidden = YES;
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(enteredBackground:) name:#"didEnterBackground" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(enteredForeground:) name:#"didEnterForeground" object:nil];
estaActivo = false;
cuentaAtras = 0.0;
}
- (void)viewDidUnload
{
[super viewDidUnload];
[[NSNotificationCenter defaultCenter] removeObserver:self];
// Release any retained subviews of the main view.
if ( [tiempo isValid] ) {
[tiempo invalidate];
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
- (IBAction)botonIniciarCuenta:(id)sender {
cuentaAtras = (NSTimeInterval)_vistaContador.countDownDuration;
remainder = cuentaAtras;
//NSLog(#"Total de segundos: %i", remainder);
afterRemainder = cuentaAtras - remainder%60;
//NSLog(#"Total segundos despues restantes: %i", afterRemainder);
tiempo = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(actualizarCuentaAtras) userInfo:nil repeats:YES];
}
- (IBAction)botonDetenerCuenta:(id)sender {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"La cuenta atrás se ha parado" message:#"Pulse Iniciar para una nueva cuenta" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:#"Aceptar" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
[self visibilidadBotones];
[tiempo invalidate];
tiempo = nil;
}
- (void)actualizarCuentaAtras {
self.botonIniciarCuenta.hidden = YES;
self.mensajeCuenta.hidden = NO;
self.tiempoRestante.hidden = NO;
self.botonDetenerCuenta.hidden = NO;
dispatch_async(dispatch_get_main_queue(), ^{
if (afterRemainder >= 0) {
afterRemainder--;
//NSLog(#"Valor restante disminuido: %i", afterRemainder);
int horas = (int)(afterRemainder/(60*60));
int minutos = (int)(((int)afterRemainder/60)- (horas * 60));
int segundos = (int)(((int)afterRemainder - (60 * minutos) - (60 * horas * 60)));
NSString *cadenaTiempo = [[NSString alloc]initWithFormat:#"%02u : %02u : %02u", horas, minutos, segundos];
self.tiempoRestante.text = cadenaTiempo;
if (afterRemainder == 0) {
[tiempo invalidate];
tiempo = nil;
[self visibilidadBotones];
[self enviarAlerta];
}
}
});
}
- (void)enteredBackground:(NSNotification *)notification
{
if (estaActivo) {
[tiempo invalidate];
date = [NSDate dateWithTimeIntervalSinceNow:cuentaAtras];
//NSLog([date description]);
self.notification = [[UILocalNotification alloc] init];
self.notification.fireDate = date;
self.notification.timeZone = [NSTimeZone defaultTimeZone];
self.notification.alertAction = #"timer fired";
self.notification.alertBody = #"timer fired!";
self.notification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:self.notification];
}
}
- (void)enteredForeground:(NSNotification *)notification
{
if (estaActivo) {
NSTimeInterval newDuration = [self.notification.fireDate timeIntervalSinceNow];
if (newDuration > 0.0) {
cuentaAtras = newDuration;
tiempo = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:#selector(actualizarCuentaAtras) userInfo:nil repeats:YES];
} else {
cuentaAtras = 0.0;
//[self.countDownPicker setHidden:NO];
//[self.countDownLabel setHidden:YES];
estaActivo = !estaActivo;
}
[self actualizarCuentaAtras];
[[UIApplication sharedApplication] cancelLocalNotification:self.notification];
}
}
- (void)enviarAlerta {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"Notificación enviada" message:#"Puede reiniciar la cuenta atrás" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:#"Aceptar" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
}
-(void)visibilidadBotones {
self.botonIniciarCuenta.hidden = NO;
self.botonDetenerCuenta.hidden = YES;
self.mensajeCuenta.hidden = YES;
self.tiempoRestante.hidden = YES;
}
#end
The code in ViewController.h is:
#interface ViewController : UIViewController {
int afterRemainder;
int remainder;
NSTimeInterval cuentaAtras;
NSTimer *tiempo;
BOOL estaActivo;
NSDate *date;
}
#property (strong, nonatomic) IBOutlet UIDatePicker *vistaContador;
#property (strong, nonatomic) IBOutlet UILabel *mensajeCuenta;
- (IBAction)botonIniciarCuenta:(id)sender;
#property (strong, nonatomic) IBOutlet UIButton *botonIniciarCuenta;
- (IBAction)botonDetenerCuenta:(id)sender;
#property (strong, nonatomic) IBOutlet UIButton *botonDetenerCuenta;
#property (strong, nonatomic) IBOutlet UILabel *tiempoRestante;
#property (strong, nonatomic) UILocalNotification *notification;
I'm starting to program in iOS, and control processes in the background for me is very complicated, but I don´t understand why the countdown works in Xcode simulator and doesn´t work on my iPhone ?
What´s wrong?
Timers don't run in the background unless you leverage some of the other background modes.
The best way to handle this is to pause it in applicationWillResignActive and make a note of the current time, and then in applicationDidBecomeActive restart it, minus the time elapsed since it was paused.
I'm using a host/client approach to using MultiPeer Connectivity.
So, when a user his the disconnect button
-(IBAction)disconnect:(id)sender {
[_appDelegate.mcManager.session disconnect];
[_arrConnectedDevices removeAllObjects];
ConnectionsViewController *game = [self.storyboard instantiateViewControllerWithIdentifier:#"ConnectionsViewController"];
[self presentViewController:game animated:YES completion:nil];
}
Now, this works fine. From the hosts point of view it receives a disconnect message in the log. and the client moves to the new view controller. And the table is updated. with this.
-(void)peerDidChangeStateWithNotification:(NSNotification *)notification{
MCPeerID *peerID = [[notification userInfo] objectForKey:#"peerID"];
NSString *peerDisplayName = peerID.displayName;
MCSessionState state = [[[notification userInfo] objectForKey:#"state"] intValue];
if (state != MCSessionStateConnecting) {
if (state == MCSessionStateConnected) {
if (_makeSureImHost) {
[_arrConnectedDevices addObject:peerDisplayName];
[_tblConnectedDevices performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:NO];
}
else {
[self sendMessageToHostWithMessage:#"deviceInfo"];
}
}
else if (state == MCSessionStateNotConnected){
if ([_arrConnectedDevices count] > 0) {
int indexOfPeer = (int)[_arrConnectedDevices indexOfObject:peerDisplayName];
[_arrConnectedDevices removeObjectAtIndex:indexOfPeer];
NSLog(#"%# Disconnected", peerDisplayName);
[_tblConnectedDevices performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:NO];
_tblConnectedDevices.frame = CGRectMake(_backgroundImage.frame.size.width / 2 - 150, self.backgroundImage.frame.size.height / 3, 300, 150);
}
}
}
}
END OF LOBBY VIEW CONTROLLER
START OF CONNECTION VIEW CONTROLLER
When a client presses to browse for local devices this runs
- (IBAction)browseForDevices:(id)sender {
[UIView animateWithDuration:0.5f
animations:^{
_searchButton.frame = CGRectMake(-100, self.backgroundImage.frame.size.height/2 + 60, 100, 35.0);
_hostButton.alpha = 0;
_modeLabel.alpha = 0;
}];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[[_appDelegate mcManager] setupPeerAndSessionWithDisplayName:[UIDevice currentDevice].name];
[[_appDelegate mcManager] advertiseSelf:false];
[[_appDelegate mcManager] setupMCBrowser];
[[[_appDelegate mcManager] browser] setDelegate:self];
_appDelegate.mcManager.browser.maximumNumberOfPeers = 1;
_appDelegate.mcManager.browser.modalTransitionStyle=UIModalTransitionStyleCrossDissolve;
[self presentViewController:[[_appDelegate mcManager] browser] animated:YES completion:nil];
});
}
When a connection is established
-(void)browserViewControllerDidFinish:(MCBrowserViewController *)browserViewController {
[_appDelegate.mcManager.browser dismissViewControllerAnimated:NO completion:^{
[self launchViewController];
}];
}
-(void)launchViewController {
LobbyViewController *lobby = [self.storyboard instantiateViewControllerWithIdentifier:#"LobbyViewController"];
[self presentViewController:lobby animated:NO completion:nil];
}
From this
-(void)peerDidChangeStateWithNotification:(NSNotification *)notification {
MCPeerID *peerID = [[notification userInfo] objectForKey:#"peerID"];
NSString *peerDisplayName = peerID.displayName;
MCSessionState state = [[[notification userInfo] objectForKey:#"state"] intValue];
if (state != MCSessionStateConnecting) {
if (state == MCSessionStateConnected) {
[self browserViewControllerDidFinish:[[_appDelegate mcManager] browser]];
}
}
else if (state == MCSessionStateNotConnected){
if ([_arrConnectedDevices count] > 0) {
int indexOfPeer = (int)[_arrConnectedDevices indexOfObject:peerDisplayName];
[_arrConnectedDevices removeObjectAtIndex:indexOfPeer];
}
}
}
Now. When a connection is made for the first time. This all works flawlessly. It connects, loads the view, host starts the game, game works fine and data is transferred perfectly.
However, if you disconnect from the lobby. Get moved to the connection viewcontroller then browse for devices again. It will connect, however the lobby viewcontroller will NOT be in the view hierarchy and will close the browser and stay in the connection view controller.
Then, to top it off, the connection has been made. yet, when it receives a message from the host, it will send the response, twice.. or three times, or four, leading me to a dead end. The only thing I can presume is that the previous session is being remembered somehow from the "clients" point of view.
Now, steps I can take to avoid this mess. If I kill the app and relaunch it I can now connect again from the clients point of view. Which leads me to believe, the problem is on the clients end.
My problem is that I have to absolutely sort this out. So a disconnect will fully remove everything from the session. So they can reconnect again. And cannot rely on a message to tell the user to restart their application. It just cannot be.
Here's my entire MCManager.m file.
#implementation MCManager
-(id)init{
self = [super init];
if (self) {
_peerID = nil;
_session = nil;
_browser = nil;
_advertiser = nil;
}
return self;
}
-(void)setupPeerAndSessionWithDisplayName:(NSString *)displayName{
_peerID = [[MCPeerID alloc] initWithDisplayName:displayName];
_session = [[MCSession alloc] initWithPeer:_peerID];
_session.delegate = self;
}
-(void)setupMCBrowser{
_browser = [[MCBrowserViewController alloc] initWithServiceType:#"chat-files" session:_session];
}
-(void)advertiseSelf:(BOOL)shouldAdvertise{
if (shouldAdvertise) {
_advertiser = [[MCAdvertiserAssistant alloc] initWithServiceType:#"chat-files"
discoveryInfo:nil
session:_session];
[_advertiser start];
}
else{
[_advertiser stop];
_advertiser = nil;
}
}
-(void)session:(MCSession *)session peer:(MCPeerID *)peerID didChangeState:(MCSessionState)state{
NSDictionary *dict = #{#"peerID": peerID,
#"state" : [NSNumber numberWithInt:state]
};
[[NSNotificationCenter defaultCenter] postNotificationName:#"MCDidChangeStateNotification"
object:nil
userInfo:dict];
}
-(void)session:(MCSession *)session didReceiveData:(NSData *)data fromPeer:(MCPeerID *)peerID{
NSDictionary *dict = #{#"data": data,
#"peerID": peerID
};
[[NSNotificationCenter defaultCenter] postNotificationName:#"MCDidReceiveDataNotification"
object:nil
userInfo:dict];
}
-(void)session:(MCSession *)session didStartReceivingResourceWithName:(NSString *)resourceName fromPeer:(MCPeerID *)peerID withProgress:(NSProgress *)progress{
}
-(void)session:(MCSession *)session didFinishReceivingResourceWithName:(NSString *)resourceName fromPeer:(MCPeerID *)peerID atURL:(NSURL *)localURL withError:(NSError *)error{
}
-(void)session:(MCSession *)session didReceiveStream:(NSInputStream *)stream withName:(NSString *)streamName fromPeer:(MCPeerID *)peerID{
}
#end
#import <MultipeerConnectivity/MultipeerConnectivity.h>
#interface MCManager : NSObject <MCSessionDelegate>
#property (nonatomic, strong) MCPeerID *peerID;
#property (nonatomic, strong) MCSession *session;
#property (nonatomic, strong) MCBrowserViewController *browser;
#property (nonatomic, strong) MCAdvertiserAssistant *advertiser;
-(void)setupPeerAndSessionWithDisplayName:(NSString *)displayName;
-(void)setupMCBrowser;
-(void)advertiseSelf:(BOOL)shouldAdvertise;
#end
If anyone knows what I'm doing wrong I'd much appreciate it. This is driving me nuts.
[[NSNotificationCenter defaultCenter] removeObserver:name:object:];
Has fixed all my problems. Hopefully helps some other people too.
With Swift, I end the multipeer session as follows (after completing checking the deinit of session tracker):
func stopSession() {
self.serviceBrowser.stopBrowsingForPeers()
self.serviceBrowser.delegate = nil
self.serviceAdvertiser.stopAdvertisingPeer()
self.serviceAdvertiser.delegate = nil
self.session.disconnect()
self.peerSessionIDs.removeAll()
self.session.delegate = nil
self.session = nil
self.multipeerConnectivityService = nil
self.serviceType = nil
}
In other words, everything that was registered and the initializer is de-initialized. I am doing this in reverse order, but I'm not sure if order is important here.
I want to check if the application is idle (user doesn't take any action for the last 30 minutes) and log out the user.
For that I have an event manager that resets a timer.
- (void)sendEvent:(UIEvent *)event {
if(event == nil) {
[self resetIdleTimer];
} else {
[super sendEvent:event];
// Only want to reset the timer on a Began touch or an Ended touch, to reduce the number of timer resets.
NSSet *allTouches = [event allTouches];
if ([allTouches count] > 0) {
// allTouches count only ever seems to be 1, so anyObject works here.
UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase;
if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded)
[self resetIdleTimer];
}
}
}
- (void)resetIdleTimer {
if (self.idleTimer) {
[self.idleTimer invalidate];
self.idleTimer = nil;
}
NSInteger maxTime = 60*30; //30 minutes
self.idleTimer = [NSTimer scheduledTimerWithTimeInterval:maxTime target:self selector:#selector(checkIfIdleTimerExceeded) userInfo:nil repeats:NO];
}
- (void)checkIfIdleTimerExceeded {
theProfileManager = [[ProfileManager alloc] init];
theProfile = [theProfileManager getProfile];
if( ! [[theProfile getStatus]isEqualToString:#"u1"]) {
if( ! [[theProfile getTheUser] isUnlimitedLogin]) {
theProfile = nil;
theUserManager = [[UserManager alloc] init];
[theUserManager setCurrentUser:[theProfile getTheUser]];
[theUserManager setCurrentUserAccount:[[theProfile getTheUser] getTheUserAccount]];
[theUserManager setCurrentUserSettings:[[theProfile getTheUser] getTheUserSettings]];
[theUserManager logoutCurrentUser];
[[MenuItemDataManager alloc] deleteJsonData];
NSNotification *msg = [NSNotification notificationWithName:#"leftPanelMsg" object:[[NSString alloc] initWithFormat:#"Home"]];
[[NSNotificationCenter defaultCenter] postNotification:msg];
[self performSelector:#selector(loadHomeView:) withObject:nil afterDelay:0.5f];
}
}
[self resetIdleTimer];
}
The checkIfIdleTimerExceeded does the log out process.
Problem: After 15 minutes I touch the screen, the resetIdleTime is called and should restart a new NSTimer. But after 15 minutes the application logs the user out.
Thanks for your help.
André.
As per your requirement of the Touches event. You should do this:
NSSet *allTouchEvents = [event allTouches];
if ([allTouchEvents count] > 0) {
// allTouchEvents count only ever seems to be 1, so anyObject works here.
UITouchPhase phase = ((UITouch *)[allTouchEvents anyObject]).phase;
if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded)
[self resetIdleTimer];
}
And in the resetIdleTimer, The
self.idleTimer = [NSTimer scheduledTimerWithTimeInterval:maxTime target:self selector:#selector(checkIfIdleTimerExceeded) userInfo:nil repeats:NO];
should be like
self.idleTimer = [NSTimer scheduledTimerWithTimeInterval:maxTime target:self selector:#selector(checkIfIdleTimerExceeded:) userInfo:nil repeats:NO];
And checkIfIdleTimerExceeded should be like:
-(void) checkIfIdleTimerExceeded :(NSTimer*)timer
{
//Do your all process and invalidate after completion
[timer invalidate];
}
I'm not sure which one of your other methods can be called beside the –resetIdleTimer in your workflow when you touch the screen, but that solution works to me as you have described to like getting it worked:
I'm seeing in the log console the –resetTimer: will called if I tap a button within 7 secs, it resets the timer properly and creates a new 7 secs timer.
the logout method will call only if I don't touch my button on the screen in 7 secs time, and the timer finally invokes the –logout: method.
- (void)resetTimer:(NSTimer *)timer {
NSLog(#"reset time...");
if (timer.isValid) [timer invalidate], _timer = nil;
_timer = [NSTimer scheduledTimerWithTimeInterval:7.f target:self selector:#selector(logout:) userInfo:nil repeats:NO];
}
//
- (void)buttonTouchedUpInside:(UIButton *)sender {
NSLog(#"touched...");
[self resetTimer:_timer];
}
//
- (void)logout:(NSTimer *)timer {
NSLog(#"logout...");
if (timer.isValid) [timer invalidate], _timer = nil;
// logout ...
}
I have a uitextlabel that is updated using an nstimer.
When I switch to another view controller (storyboard segue) and back again the text label is no longer updated (returns to default text), even though the timer continues to run.
The timer is writing a value to the uitextlabel which stops working after switching.
NOTE: the updateTimerLabel method continues to output the correct info but the label is not updated.
headerfile
NSString *timerTicksForCounter;
- (void)viewDidLoad
{
[super viewDidLoad];
[self updateTimerLabel];
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self updateTimerLabel];
}
- (void) startLastConUpdater
{
lastCTimer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:#selector(updateTimer)
userInfo:nil
repeats:YES];
}
-(void) updateTimerLabel
{
NSLog(#"timer: %#", timerTicksForCounter);
if (timerTicksForCounter) {
NSLog(#"timer not null");
mainTimerLabel.text = timerTicksForCounter;
}
}
- (void)updateTimer
{
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:stopDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"mm:ss"];
timerTicksForCounter = [dateFormatter stringFromDate:timerDate];
[self updateTimerLabel];
}
update your textField text in
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self updateLabel];
}
First Declare
NSTimer * countdownTimer;
NSUInteger remainingTicks;
- (void)viewDidLoad
{
[super viewDidLoad];
remainingTicks = 60;
[self updateLabel];
countdownTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self selector: #selector(handleTimerTick) userInfo: nil repeats: YES];
}
-(void)handleTimerTick
{
remainingTicks--;
[self updateLabel];
if (remainingTicks <= 0) {
[countdownTimer invalidate];
countdownTimer = nil;
}
}
-(void)updateLabel
{
timeLabel.text = [[NSNumber numberWithUnsignedInt: remainingTicks] stringValue];
}
//sent notification
[[NSNotificationCenter defaultCenter] removeObserver:self];
**//Get (Retrive) Notification**
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(receiveTestNotification:)
name:#"TestNotification"
object:nil];
//Get notification method.
- (void) receiveTestNotification:(NSNotification *) notification
{
// [notification name] should always be #"TestNotification"
// unless you use this method for observation of other notifications
// as well.
if ([[notification name] isEqualToString:#"TestNotification"])
NSLog (#"Successfully received the test notification!");
**//Here write your code for update textfield**
}