IOS Time Calibration Solution

Source: Internet
Author: User
Tags add time local time

Background

In IOS development, there is a problem to consider when it comes to system time: Yes. Some businesses do not need to be, or can be based on user time, such as the time of the animation, some of the calendar class applications. But most e-commerce-related businesses do not directly use the time on the device, but need to calibrate with the server time, for example:

    • Interval judgment: Some promotional promotions need to be judged on the app's current period of activity. If the user device time is not allowed, will give the user wrong information, resulting in a complaint.
    • Countdown: Various seconds to kill, limited time sales, unpaid orders, such as the expiration of the countdown. If the user device time is not allowed, will bring the countdown after the end of the Refresh page, the state has not changed the problem. You can test the e-commerce giant's app, the countdown is still correct after any dial-up table.
    • Synchronization: If the need for data synchronization, equipment time is not allowed to correctly judge the data of the old and new relationship, may let the old data overwrite the new data, resulting in data loss.
    • Request Timestamp: For paging data, a common solution is to add time-stamped parameters to the request list, and background filtering displays only the data after the timestamp, in order to prevent the data from being garbled when the newly inserted data is being paged. If the user device table is slow, the latest data is not displayed, causing the new publication to not appear in the list.

It can be seen that the need for this is very common. But it's not hard to realize, so share our experience here.

Solution Solutions

This is called a solution because it does not add a few lines of code to the app side, but rather the front and back end mates. The approximate idea is as follows:

    1. Backend needs to do: Each network request returns data with the server's current timestamp
    2. The app-side network framework takes the timestamp out of the public mediation of the network request
    3. Caches the difference between server time and local time to local
    4. When you need to use time, use the local time and the cache time difference to figure out the appropriate server times
Network Request callback

The server's timestamp can be added to the response body as a public field. In my project, I put it in the response header because of a small number of GET requests. The code looks like this:

+ (void)handleSuccessResponse:(id)responseObject operation:(AFHTTPRequestOperation *)operation responseType:(Class)responseClass success:(void (^)(id))successBlock failure:(void (^)(NSError *))failureBlock { long long timestamp = [[operation.response.allHeaderFields objectForKey:@"Response-Timestamp"] longLongValue]; [HAMDateTimeUtils updateServerTime:timestamp];}

Updates the cache of the time difference for each network request success.

A small point of note is that handling timestamp is best always with a long long type. Because timestamp is traditionally in milliseconds (although Nstimeinteval is in seconds in the wonderful system of IOS), long and Nsinteger are not stored on 32-bit systems and will overflow. Of course, the 32-bit system now has a less common device.

Cache of Time Difference

When updating the cache, save the server time and the local current difference in the singleton.

Hamdatetimeutils.m
- (void)updateServerTime:(long long)timestamp {    NSTimeInterval timeInteval = timestamp / 1000.0 - [[NSDate date] timeIntervalSince1970]; [self sharedInstance].timeIntevalDifference = timeInteval;}
Provide calibrated time

When a time is required, the calibrated time is calculated based on the current time and the cached difference:

Hamdatetimeutils.m
+ (nsdate*) currentTime {nsdate* serverdate = [nsdate Datewithtimeintervalsincenow:[self sharedinstance].timeintevaldifference]; return serverdate;} //in milliseconds + (long long) Currenttimestamp {nstimeinterval localtime = [[NSDate Date] TIMEINTERVALSINCE1970]; nstimeinterval timedifference = [Wnydatetimeutils sharedinstance]. Timeintevaldifference; return (long long) (( Localtimestamp + timedifference) * 1000);}        

You can only call [HAMDateTimeUtils currentTime] or be used [HAMDateTimeUtils currentTimeStamp] .

Discuss
    • Q: Is this time accurate?
      A: There will be a certain error. The reason for this is that the timestamp returned by the server is the time when the data is returned from the server, and there is a little delay when the client receives it. But for our backstage, this delay generally <100 MS, has no effect on our business.
      If the accuracy requirements are higher, you can consider using a special pair-time interface, do not know whether the National observatory has ...
      In addition, this approach to the time is only used to optimize the UI level of display, not to prevent malicious user tampering. Always remember that the timestamp of the client is untrusted, and the backend business is always using the server's time.

    • Q: When caching, why is there only a singleton, not persistent storage?
      A: I have also considered this, mainly feel that the time difference may change when starting again, the feeling of persistence is not much necessary. If you feel it is necessary, you can also save a copy in the Userdefault, when you start to remove it.

IOS Time Calibration Solution

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.