I found this outdated question (-> Swift get server time) while looking for a simple way to get the current time.
I've updated the code from (-> Answer) to the current Swift version and now it looks like this:
func serverTimeReturn(completionHandler:@escaping (_ getResDate: NSDate?) -> Void){
let url = NSURL(string: "http://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"
var serverTime = dFormatter.date(from: contentType)
completionHandler(serverTime as! NSDate)
}
}
task.resume()
}
... calling with ...
serverTimeReturn { (getResDate) -> Void in
var dFormatter = DateFormatter()
dFormatter.dateStyle = DateFormatter.Style.long
dFormatter.timeStyle = DateFormatter.Style.long
dFormatter.timeZone = NSTimeZone(abbreviation: "GMT") as! TimeZone
var dateGet = dFormatter.string(from: getResDate as! Date)
print("Formatted Time : \(dateGet)")
}
But I still get this error message:
Fatal error: Unexpectedly found nil while unwrapping an Optional value
--> Thread 3: EXC_BREAKPOINT (code=1, subcode=xyz)
while calling completionHandler(serverTime as! NSDate)
I have no clue how to get rid of this error soo, any help would be very appreciated!