Get the server’s current time with Swift 4.X URLSession

i0S Swift Issue

Taking the server’s time when you create an application needs to synchronize the time between the client and server. The following short code will retrieve the server’s time via URLSession.

func returnServerTime(completionHandler:@escaping (_ getResDate: NSDate?) -> Void){
    let stringurl = "http://" + "Your Server IP"
    let url = NSURL(string: stringurl)
    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"
            let serverTime = dFormatter.date(from: contentType)
            completionHandler(serverTime! as NSDate)
        }else{
            return
        }
    }
    task.resume()
}

Usage: Put the code below into any function you want to use.

self.returnServerTime { (getResDate) -> Void in
    let dFormatter = DateFormatter()
    dFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss"
    dFormatter.timeZone = NSTimeZone(abbreviation: "japanese") as TimeZone?
    let currentTime = dFormatter.string(from: getResDate! as Date)
}// End of Send to server!