同步请求当前网络北京时间

基于 http://www.jianshu.com/p/ffc758b8eb0e 的修改。

由于使用[NSDate date]来获取当前时间是不准确的,因为用户可能会将设备的时间修改了,[NSDate date]的值是基于当前设备设定的时间。
所以只能通过网络的来获取当前时间。

  • ATS需添加域名白名单m.baidu.com
  • 使用信号量同步NSURLSession 网络请求
  • GMT时区转换成当前中国北京时区
/*!
 获取网络的当前北京时间(不受因用户改设备时间影响,准确),同步请求
 ATS需添加域名白名单m.baidu.com
 NSExceptionDomains
 
 m.baidu.com
 
 NSExceptionAllowsInsecureHTTPLoads
 
 
 
 */
+ (instancetype)getCurrentPlus8InterneDate{
    NSString *urlString = @"http://m.baidu.com";
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString: urlString]];
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    [request setTimeoutInterval: 2];
    [request setHTTPShouldHandleCookies:FALSE];
    [request setHTTPMethod:@"GET"];
    __block NSHTTPURLResponse *mResponse;
    
    dispatch_semaphore_t semaphare = dispatch_semaphore_create(0); //使用信号量来同步请求
    
    [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        mResponse = (NSHTTPURLResponse *)response;
        dispatch_semaphore_signal(semaphare);
    }] resume];
    dispatch_semaphore_wait(semaphare, DISPATCH_TIME_FOREVER);
    
    NSString *date = [[mResponse allHeaderFields] objectForKey:@"Date"];
    NSDateFormatter *dMatter = [[NSDateFormatter alloc] init];
    dMatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [dMatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"]; //Tue, 17 Jan 2017 07:22:52 GMT
    NSDate * netDate = [dMatter dateFromString:date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: netDate];
    NSDate *localeDate = [netDate  dateByAddingTimeInterval: interval];
    return localeDate;
}

也可以通过自己服务器,和获取内核kernel的时间算出时间偏移,来算出准确的时间段

//ObjC
NSTimeInterval systemUptime =[[NSProcessInfo processInfo] systemUptime];
//swift
var systemUptime = ProcessInfo().systemUptime;

参考 http://www.jianshu.com/p/82475b5a7e19

你可能感兴趣的:(同步请求当前网络北京时间)