iOS internal clock

Source: Internet
Author: User

1. What is an internal clock

when we do iOS development, we often have to deal with time,[NSDate Date] is one of the ways we used to take time, but [NSDate Date] This method only takes the current time of the system. That is: the current time of our mobile phone is what time, the value taken out, is how much.

What if the user changes the time of the system? So [NSDate Date] take out the value, or we want it??? In the development of some applications, we can not take the network time and rely on the system time to be tampered with without the network state. So at this point, we're going to have to customize one of our own internal clocks inside the program.

2. The idea of implementing an internal clock

1. To have a time as the basic reference point (the general application will be dealing with the server, so send a request to the server, the time to fetch the server is more appropriate)

2. To have a mark point (generally take standby time)

3. Every time you enter the program, or log in, take the time to save the server, and then take the current standby time to save, each time to obtain the current time, then take the standby time and the previous storage standby time compared to obtain the difference. By adding a difference to the stored server time, you get the current time you want.

3. Concrete implementation Steps

0. Macros used:

Power-On time # swstarttime  @ "StartTime"//server time # define Swservertime @ "Servertime"//Log on when the standby length # define Swsincenow @ " Sincenow "

1. Get Standby duration


/** * Standby time (time interval from the moment the system starts) */+ (time_t) uptime{ struct timeval boottime; int mib[2] = {ctl_kern, kern_boottime}; size_t size = sizeof (boottime); time_t now; time_t uptime =-1; (void) time (&now); if (Sysctl (MIB, 2, &boottime, &size, NULL, 0)! =-1 && boottime.tv_sec! = 0) { uptime = Now-bo ottime.tv_sec; } return uptime; }

2. Storage server time and standby duration

/** *  Storage server time and Standby duration * *  @param servertime server time */+ (void) Firsttimewithlogin: (NSString *) servertime{        Nstimeinterval timer = (nstimeinterval) [self uptime];        NSString *sincenow = [NSString stringwithformat:@ "%f", timer];                Nsuserdefaults *userdefaults = [Nsuserdefaults standarduserdefaults];        Store the server time acquired at login        [userdefaults setobject:servertime forkey:swservertime];        The standby time obtained when storing the login        [userdefaults setobject:sincenow forkey:swsincenow];   }

3. Get current time (base on server time)

+ (NSDate *) dateofnow{    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];    [Formatter setdateformat:@ "Yyyy-mm-dd HH:mm:ss"];        Nsuserdefaults *userdefaults = [Nsuserdefaults standarduserdefaults];    Remove the server time obtained at login    nsstring * servertext = [userdefaults objectforkey:swservertime];    NSDate *firstserver = [formatter datefromstring:servertext];        NSString *firsttext = [Userdefaults objectforkey:swsincenow];    CGFloat first = Firsttext.floatvalue;    Nstimeinterval timer = (nstimeinterval) [self uptime];        CGFloat second = (cgfloat) timer;        Difference value    cgfloat finaly = Second-first;    Nstimeinterval interval = (nstimeinterval) finaly;        The last time    nsdate *finalydate = [Firstserver datebyaddingtimeinterval:interval];    return finalydate;}

4. Deep discussion

    • Why not systemuptime this method for getting standby time?

Answer: SystemUpTime this way to get the standby time when our device deep sleep, the value obtained will be error, and the above method I use does not. Pro Test!!!

    • What if I want to get the phone's boot time?

Answer:

/** * Get boot time*/+ (NSString *) getuptime{NSString*Proc_usetiem;    intnia[4] = {Ctl_kern, Kern_proc, Kern_proc_pid,0}; size_t Miblen=4;size_t size; //returns 0, succeeds, returns-1, fails    intst = Sysctl (MIB, Miblen, NULL, &size, NULL,0); structKinfo_proc * Process =NULL; structKinfo_proc * newprocess =NULL;  Do{size+ = size/Ten; Newprocess=realloc (process, size); if(!newprocess) {            if(process) {free (process); Process=NULL; }            returnNil; } Process=newprocess; St= Sysctl (MIB, Miblen, process, &size, NULL,0); }     while(St = =-1&& errno = =Enomem); if(St = =0)    {        if(Size%sizeof(structKINFO_PROC) = =0)        {            intnprocess = size/sizeof(structKinfo_proc); if(nprocess) { for(inti = nprocess-1; I >=0; i--) {@autoreleasepool {//the time of the process                        Doublet = process->kp_proc.p_un.__p_starttime.tv_sec; Doubles = process->kp_proc.p_un.__p_starttime.tv_usec; Doublefinaly = t + S *0.000001;
convert it to a specific time Proc_usetiem=[self timewithboot:finaly]; }} free (process); Process=NULL; returnProc_usetiem; } } } returnNil;}

 /*  * * to specific time  */ + (NSString *) Timewithboot: (double  )    interval{nsdateformatter  *format = [[NSDateFormatter Alloc]init]; Format.timezone  = [nstimezone timezonewithname:@ " shanghai    //  note order   @ "Yyyy-mm-dd HH:mm:ss. SSS "];  
    *date = [NSDate datewithtimeintervalsince1970:interval];     *boottime = [format stringfromdate:date];     return Boottime;}

PS: If you have any questions, please leave a message or follow my Sina Weibo http://weibo.com/3216725234 private messages!!!!

iOS internal clock

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.