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