iphone - Displaying the time duration the app was in background -
i new ios programming, , trying make simple app know more lifecycle , different states. app store current timestamp when app running, , whenever goes background , comes up, show message "good see after xx minutes".
now, approach this, @ beginning there timestamp stored in variable, , when viewdidload() method called, check timestamp current timestamp , display subtracted value.
when app going background, change value of local timestamp variable in viewdidunload() method , when coming compare timestamps , display message.
any pointers regarding correct approach of doing this?
use below code in appdelegate.m file
put below method
-(void)mincalculation_backgroundtime:(nsstring *)backgroundtime forgroundtime:(nsstring *)foregroundtime { nsdateformatter *dateformat = [[nsdateformatter alloc]init]; [dateformat setdateformat:@"mm/dd/yyyy hh:mm:ss"]; nsdate *lastdate = [dateformat datefromstring:foregroundtime]; nsdate *todaysdate = [dateformat datefromstring:backgroundtime]; nstimeinterval lastdiff = [lastdate timeintervalsincenow]; nstimeinterval todaysdiff = [todaysdate timeintervalsincenow]; nstimeinterval datediff = lastdiff - todaysdiff; int min = datediff/60; nslog(@"good see after %i minutes",min); }
and replace below 2 methods
- (void)applicationdidenterbackground:(uiapplication *)application { nsdateformatter *dateformat = [[nsdateformatter alloc]init]; [dateformat setdateformat:@"mm/dd/yyyy hh:mm:ss"]; nsstring *backgroundtime = [dateformat stringfromdate:[nsdate date]]; [[nsuserdefaults standarduserdefaults]setvalue:backgroundtime forkey:@"backgroundtime"]; // use method release shared resources, save user data, invalidate timers, , store enough application state information restore application current state in case terminated later. // if application supports background execution, method called instead of applicationwillterminate: when user quits. } - (void)applicationwillenterforeground:(uiapplication *)application { nsdateformatter *dateformat = [[nsdateformatter alloc]init]; [dateformat setdateformat:@"mm/dd/yyyy hh:mm:ss"]; nsstring *foregroundtime = [dateformat stringfromdate:[nsdate date]]; nsstring *backgroundtime = [[nsuserdefaults standarduserdefaults]valueforkey:@"backgroundtime"]; [self mincalculation_backgroundtime:backgroundtime forgroundtime:foregroundtime]; // called part of transition background inactive state; here can undo many of changes made on entering background. }
try problem solve
Comments
Post a Comment