#pragma mark --请求网络时间戳
-(void)getInternetDateWithSuccess:(void(^)(NSTimeInterval timeInterval))success
failure:(void(^)(NSError *error))failure{
//1.创建URL
NSString *urlString = @"http://m.baidu.com";
urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//2.创建request请求对象
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString: urlString]];
[request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
[request setTimeoutInterval:5];
[request setHTTPShouldHandleCookies:FALSE];
[request setHTTPMethod:@"GET"];
//3.创建URLSession对象
NSURLSession *session = [NSURLSession sharedSession]; //4.设置数据返回回调的block
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error == nil && response != nil) {
//这么做的原因是简体中文下的手机不能识别“MMM”,只能识别“MM”
NSArray *monthEnglishArray = @[@"Jan",@"Feb",@"Mar",@"Apr",@"May",@"Jun",@"Jul",@"Aug",@"Sept",@"Sep",@"Oct",@"Nov",@"Dec"];
NSArray *monthNumArray = @[@"01",@"02",@"03",@"04",@"05",@"06",@"07",@"08",@"09",@"09",@"10",@"11",@"12"];
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSDictionary *allHeaderFields = [httpResponse allHeaderFields];
NSString *dateStr = [allHeaderFields objectForKey:@"Date"];
dateStr = [dateStr substringFromIndex:5];
dateStr = [dateStr substringToIndex:[dateStr length]-4];
dateStr = [dateStr stringByAppendingString:@" +0000"];
//当前语言是中文的话,识别不了英文缩写
for (NSInteger i = 0 ; i < monthEnglishArray.count ; i++) {
NSString *monthEngStr = monthEnglishArray[i];
NSString *monthNumStr = monthNumArray[i];
dateStr = [dateStr stringByReplacingOccurrencesOfString:monthEngStr withString:monthNumStr];
}
NSDateFormatter *dMatter = [[NSDateFormatter alloc] init];
[dMatter setDateFormat:@"dd MM yyyy HH:mm:ss Z"];
NSDate *netDate = [dMatter dateFromString:dateStr];
NSTimeInterval timeInterval = [netDate timeIntervalSince1970];
dispatch_async(dispatch_get_main_queue(), ^{
success(timeInterval);
});
}else{
dispatch_async(dispatch_get_main_queue(), ^{
failure(error);
});
}
}];
//4、执行网络请求
[task resume];
}
请求网络时间戳
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 代码地址https://github.com/chenwei007/AFN-.git 中心化的设计思想,代码简洁统...
- http://www.jianshu.com/p/11f7f25ec63chttp://www.jianshu.c...
- 下面选了最近十年里,十位名人所做的毕业演讲。那么多的故事与经历,其实只想告诉你一件事: 面对迷茫和不确定的未来,我...
- Alamofire的默认超时时间是30秒,我需要设定自己的超时时间 在自己的二次封装类里面设置一个全局manage...