0

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:

  1. Look up the current date and time in "UTC" on google's servers.
  2. Ensure I have retrieved the data before continuing
  3. 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!

Justin
  • 167
  • 2
  • 12
  • Which line do you get the `nil` error on? – Malik Apr 26 '18 at 03:21
  • @Malik When I get the 'nil' error, it's coming from the line 'if let contentType = httpsResponse!.allHeaderFields["Date"] as? String', where it said something about the headers being nil?? Sadly, I'm not even entirely sure how the date is even retrieved from Google so I can't offer more insight... This code was for the most part copied from another stack overflow answer. I also get error codes 1001 and 1002 sometimes (I think when I get that nil error... which didn't happen at the time of my post). – Justin Apr 26 '18 at 11:23

1 Answers1

0

Nothing is wrong with your code. You are getting error code -1009 which means your internet connection is not established.

NSURLErrorNotConnectedToInternet

Returned when a network resource was requested, but an internet connection is not established and cannot be established automatically, either through a lack of connectivity, or by the user's choice not to make a network connection automatically.

Community
  • 1
  • 1
Chanchal Chauhan
  • 1,332
  • 9
  • 22
  • Hmm, that seems strange (as my internet is very strong and I have never lost it on any of my devices)... If I exit the app while still running it through Xcode, any of my other network-reliant apps still work... :/ I suppose it didn't happen on this run, but I also get error codes 1001 and 1002 periodically. – Justin Apr 26 '18 at 11:18
  • -1001 is for `NRURLErrorTimedOut` -1002 is for `NRURLErrorUnsupportedURL` You can check other error codes [link Here](https://stackoverflow.com/questions/6778167/undocumented-nsurlerrordomain-error-codes-1001-1003-and-1004-using-storeki) – Chanchal Chauhan Apr 26 '18 at 11:30
  • Thanks for the clarification :) Do you happen to know why "https://www.google.com" would be 'unsupported' at random times based on my code? And why the request would time out? When the error occurs (and my app crashes), it's after having JUST called that code and there is no apparent delay at all. I'm running that function (retrieving date and time) whenever I close (enter background) or open (enter foreground) my app. Thanks for helping me understand! – Justin Apr 26 '18 at 12:16
  • Can you check `httpsResponse?.statusCode`. In my machine, It's working fine and I am getting 200. – Chanchal Chauhan Apr 26 '18 at 13:00
  • I am also getting 200 for `httpsResponse?.statusCode`. I find that I get all these errors after this procedure: Tap the home button (to exit my app)... It calls that function when I do... and then if I wait too long (about 10 seconds) to reopen the app (where the function is called again) it crashes with all those network errors? It's fine if I reopen it within several seconds though... – Justin Apr 27 '18 at 00:51
  • Make your httpResponse optional. It prevents your app from crash. `httpsResponse?.allHeaderFields["Date"] as? String` – Chanchal Chauhan Apr 27 '18 at 05:40
  • When you enter in background and stay for long then your app goes in suspended state. It suspend any dispatch queues or operation queues executing non-critical code. This is the reason, you are getting http error. – Chanchal Chauhan Apr 27 '18 at 06:19
  • 1
    Awesome thanks! I couldn't think of any possible reasons why it would be crashing (as what happens during an app's different states is a little bit abstract)... But this makes sense and clearly points out a possible issue. I'll see if that does the trick. :) – Justin Apr 27 '18 at 12:20