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()
}