Is there a way to get a server time to use with swift. I want to set a static time based on a server. so that even if a user changes the time zone and the date, it wouldn\'t
You shouldn't make the same network call every time you need to get corrected datetime.
So I would do like below, so I can call setSeverDate() only when I need to correct datetime:
var serverDate = Date() {
didSet {
let possibleNow = Date()
gap = possibleNow.distance(to: serverDate)
}
}
var gap: TimeInterval = 0
var correctedDate: Date {
let possibleNow = Date()
//Ignores network delay time same with or less than 2 seconds
let now = abs(gap) > 2 ? possibleNow.advanced(by: gap) : possibleNow
//For Debugging
print("\(possibleNow) + \(gap) = \(now)")
return now
}
func setServerDate() {
let url = URL(string: "https://www.google.com")
URLSession.shared.dataTask(with: url!) { _, response, _ in
let httpResponse = response as? HTTPURLResponse
if let contentType = httpResponse!.allHeaderFields["Date"] as? String {
let formatter = DateFormatter()
formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
formatter.timeZone = TimeZone.current
serverDate = formatter.date(from: contentType) ?? Date()
} else {
print("getting google server date failed")
serverDate = Date()
}
}.resume()
}
Based on this link https://github.com/freak4pc/NSDate-ServerDate i wrote the code for swift. Tried and tested. And it works.
override func viewDidLoad() {
super.viewDidLoad()
//call ServerTimeReturn function
serverTimeReturn { (getResDate) -> Void in
var dFormatter = NSDateFormatter()
dFormatter.dateStyle = NSDateFormatterStyle.LongStyle
dFormatter.timeStyle = NSDateFormatterStyle.LongStyle
dFormatter.timeZone = NSTimeZone(abbreviation: "GMT")
var dateGet = dFormatter.stringFromDate(getResDate)
println("Formatted Time : \(dateGet)")
}
}
func serverTimeReturn(completionHandler:(getResDate: NSDate!) -> Void){
let url = NSURL(string: "http://www.google.com")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
let httpResponse = response as? NSHTTPURLResponse
if let contentType = httpResponse!.allHeaderFields["Date"] as? String {
var dFormatter = NSDateFormatter()
dFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
var serverTime = dFormatter.dateFromString(contentType)
completionHandler(getResDate: serverTime)
}
}
task.resume()
}
func getServerTimer(completion:@escaping (Date?)->()) {
serverTimeReturn { date -> Void in
let dFormatter = DateFormatter()
dFormatter.dateStyle = .long
dFormatter.timeStyle = .long
dFormatter.timeZone = TimeZone(abbreviation: "GMT")
if let date = date {
let dateGet = dFormatter.string(from: date)
completion(date)
print("Formatted Time : \(dateGet)")
} else {
completion(nil)
}
}
}
func serverTimeReturn(completionHandler:@escaping (_ getResDate: Date?) -> Void) {
let url = NSURL(string: "https://www.google.com")
let task = URLSession.shared.dataTask(with: url! as URL) {(data, response, error) in
let httpResponse = response as? HTTPURLResponse
if let contentType = httpResponse!.allHeaderFields["Date"] as? String {
let dFormatter = DateFormatter()
dFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
dFormatter.locale = Locale(identifier: "en-US")
if let serverTime = dFormatter.date(from: contentType) {
completionHandler(serverTime)
} else {
completionHandler(nil)
}
}
}
task.resume()
}