编程技术记录

世界你好!

头文件

//
//  ZLNetworkTime.h
//
//  Created by zxs.zl on 2018/3/12.
//

#import <Foundation/Foundation.h>

@interface ZLNetworkTime : NSObject

+(void)startSyncTimeFromNetwork;
+(BOOL)syncTimeFromNetworkDone;

+(NSTimeInterval)timeIntervalSince1970;
@end

实现文件

//
//  ZLNetworkTime.m
//
//  Created by zxs.zl on 2018/3/12.
//

#if ! __has_feature(objc_arc)
#error This file must be compiled with ARC. Either turn on ARC for the project or use -fobjc-arc flag
#endif

#import "ZLNetworkTime.h"

struct _ZLTimeBase_
{
    _ZLTimeBase_()
    {
        init_state = not_init;
        init_count = 0;
    }

    NSTimeInterval systemUptimeBase;
    NSTimeInterval networkTimBbase;
    enum
    {
        not_init,
        initing,
        inited,
    } init_state;
    int init_count;
}s_timeBase;

@implementation ZLNetworkTime

+(NSTimeInterval)timeIntervalSince1970
{
    if (s_timeBase.init_state == s_timeBase.inited)
        return s_timeBase.networkTimBbase + [[NSProcessInfo processInfo] systemUptime] - s_timeBase.systemUptimeBase;
    else
        return [[NSDate date] timeIntervalSince1970];
}

+(BOOL)syncTimeFromNetworkDone
{
    return s_timeBase.init_state == s_timeBase.inited;
}

+(void)startSyncTimeFromNetwork
{
    if (s_timeBase.init_state !=  s_timeBase.not_init)
        return;

    if (s_timeBase.init_count >= 3)
        return;

    @synchronized(self){
        if (s_timeBase.init_state !=  s_timeBase.not_init)
            return;
        s_timeBase.init_state = s_timeBase.initing;
    }

    s_timeBase.init_count++;

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    config.timeoutIntervalForRequest = 3;
    config.requestCachePolicy = NSURLRequestReloadIgnoringCacheData;
    NSURLSession * session  = [NSURLSession sessionWithConfiguration:config];
    NSURL * url = [NSURL URLWithString:@"http://time.tianqi.com/"];

    NSTimeInterval systemUptime = [[NSProcessInfo processInfo] systemUptime];
    NSURLSessionDataTask * dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse*)response;
        if ([httpResponse isKindOfClass:[NSHTTPURLResponse class]] && httpResponse.statusCode == 200 )
        {
            NSString * dateStr = httpResponse.allHeaderFields[@"Date"];
            if (dateStr.length > 0)
            {
                //Mon, 12 Mar 2018 07:21:32 GMT
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                formatter.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
                [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
                [formatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss 'GMT'"];

                NSDate *date = [formatter dateFromString:dateStr];
                if (date)
                {
                    s_timeBase.systemUptimeBase = [[NSProcessInfo processInfo] systemUptime];
                    s_timeBase.networkTimBbase = [date timeIntervalSince1970] + s_timeBase.systemUptimeBase - systemUptime;
                    s_timeBase.init_state = s_timeBase.init_state;
                    return;
                }

            }
        }
        s_timeBase.init_state = s_timeBase.not_init;
    }];
    [dataTask resume];
}

@end

发表回复

© Beli. All Rights Reserved.