I found this other question here which has a good write-up, however it describes how to use completion handlers in a urlSession in order to segue... but I was having a hard time applying it to my case scenario.
What I want to do:
- Look up the current date and time in "UTC" on google's servers.
- Ensure I have retrieved the data before continuing
- Hold that retrieved data (date and time) in a string variable.
What I've written so far in code works... sometimes... but it's not robust. I'll often get a crash, and from my limited knowledge, I was able to research the fact that it may have to do with the task continuing on before the data has actually been retrieved (sometimes it says what I was looking up is 'nil').
Here is the part where I call the function to do the fetch:
func handleDateAndTimeFetch (fetch: String, calculate: Bool) {
serverTimeReturn { (getResDate) -> Void in //Handles the value received from Google and formats it
let dFormatter = DateFormatter()
dFormatter.dateStyle = .short
dFormatter.timeStyle = .medium
dFormatter.timeZone = TimeZone(abbreviation: "UTC")
let dateAndTimeNow = dFormatter.string(from: getResDate!)
}
}
...and here is the function:
//Call Google's server for the current date & time in UTC (Coordinated Universal Time)
func serverTimeReturn(completionHandler:@escaping (_ getResDate: Date?) -> Void){
let url = URL(string: "https://www.google.com")
let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
let httpsResponse = response as? HTTPURLResponse
if let contentType = httpsResponse!.allHeaderFields["Date"] as? String {
let dFormatter = DateFormatter() //A formatter object
dFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
let serverTime = dFormatter.date(from: contentType)
completionHandler(serverTime)
}
}
print("Retrieved date value")
task.resume()
}
...And finally, here are the errors I get the odd time. If you're able, can you also help me understand what these errors are saying exactly?:
2018-04-25 21:05:55.071137-0400 JeegO[8768:3548654] TIC TCP Conn Failed [3:0x1c0176200]: 1:50 Err(50)
2018-04-25 21:05:55.071486-0400 JeegO[8768:3548654] Task <5C958839-0A62-4E06-A811-8ED9D8A4709C>.<1> HTTP load failed (error code: -1009 [1:50])
2018-04-25 21:05:55.078817-0400 JeegO[8768:3548645] Task <5C958839-0A62-4E06-A811-8ED9D8A4709C>.<1> finished with error - code: -1009
(lldb)
I want to ensure I can retrieve this simple data (Date & Time) before I continue on with my app, so I REALLY do appreciate your help in solving this little problem so I can move on in confidence :)
Thanks so much!