IOS Internal Clock

Source: Internet
Author: User

IOS Internal Clock
1. what is an internal clock? In our iOS development process, we often have to deal with time. [NSDate date] is a common method for getting time, however, the [NSDate date] method can only take the current time of the system. That is to say, the current time of our mobile phone is what the value is. What if the user changes the system time? Then, do we still want the value obtained from [NSDate date ??? In the development of some applications, we can tamper with the network time and system time when there is no network. Therefore, we need to customize an internal clock in the program. 2. how to implement internal clock 1. there must be a time as a basic reference point (generally, applications will deal with the server, so sending requests to the server is suitable for obtaining the server time. there must be a marking point (usually taking the standby duration) 3. every time you enter the program or log on to the server, save the server time and the current standby time. Each time you want to get the current time, then compare the standby duration with the standby duration of the previous storage to obtain the difference. Add the storage server time to the difference to obtain the desired current time. 3. Specific implementation step 0. Macros used:

// Start time # define SWStartTime @ "startTime" // server time # define SWServerTime @ "serverTime" // standby time during logon # define SWSinceNow @ "sinceNow"

 

1. Obtain the standby duration
<Br>/*** standby time (the time interval obtained 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-boottime. 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 obtained during logon [UserDefaults setObject: serverTime forKey: SWServerTime]; // store the standby time obtained during logon [UserDefaults setObject: sinceNow forKey: SWSinceNow];}

 

3. Obtain the current time (based on the server time)
+ (NSDate *) dateOfNow {NSDateFormatter * formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat: @ "yyyy-MM-dd HH: mm: ss"]; NSUserDefaults * UserDefaults = [NSUserDefaults standardUserDefaults]; // retrieve the server time obtained during logon NSString * serverText = [UserDefaults objectForKey: SWServerTime]; NSDate * FirstServer = [formatter dateFromString: serverText]; NSString * firstText = [UserDefaults objectForKey: SWSinceNow]; CGFloat first = firstText. floatValue; effectimer = (NSTimeInterval) [self uptime]; CGFloat second = (CGFloat) timer; // difference CGFloat finaly = second-first; NSTimeInterval interval = (NSTimeInterval) finaly; // last time NSDate * finalyDate = [FirstServer dateByAddingTimeInterval: interval]; return finalyDate ;}

 

4. In-depth discussion on why don't SystemUptime be used to obtain the standby time? Answer: SystemUptime, which is used to obtain the standby time, has an error in the value obtained during deep sleep on our device. The method I used above does not. Test it !!! What if I want to get the start time of my mobile phone? Answer:
/*** Get boot time */+ (NSString *) getUpTime {NSString * proc_useTiem; int mib [4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, 0 }; size_t miblen = 4; size_t size; // return 0, success; Return-1, failure int st = sysctl (mib, miblen, NULL, & size, NULL, 0 ); struct kinfo_proc * process = NULL; struct kinfo_proc * newprocess = NULL; do {size + = size/10; newprocess = realloc (process, size); if (! Newprocess) {if (process) {free (process); process = NULL;} return nil;} process = newprocess; st = sysctl (mib, miblen, process, & size, NULL, 0) ;}while (st =-1 & errno = ENOMEM); if (st = 0) {if (size % sizeof (struct kinfo_proc) = 0) {int nprocess = size/sizeof (struct kinfo_proc); if (nprocess) {for (int I = nprocess-1; I> = 0; I --) {@ autoreleasepool {// process time double t = process-> kp_proc.p_un. _ p_starttime. TV _sec; double s = process-> kp_proc.p_un. _ p_starttime. TV _usec; double finaly = t + s * 0.000001; // convert it to proc_useTiem = [self timeWithBoot: finaly];} free (process); process = NULL; return proc_useTiem ;}}return nil ;}

 

/*** Convert to specific time */+ (NSString *) timeWithBoot :( double) interval {NSDateFormatter * format = [[NSDateFormatter alloc] init]; format. timeZone = [NSTimeZone timeZoneWithName: @ "shanghai"]; [format setDateStyle: NSDateFormatterMediumStyle]; [format setTimeStyle: nsdateformatter1_style]; // pay attention to the sequence [format setDateFormat: @ "yyyy-MM-dd HH: mm: ss. SSS "]; NSDate * date = [NSDate dateWithTimeIntervalSince1970: interval]; NSString * bootTime = [format stringFromDate: date]; return bootTime ;}

 

 

Related Article

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.