1

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!

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Jonas0000
  • 1,085
  • 1
  • 12
  • 36
  • "Fatal error: Unexpectedly found nil while unwrapping an Optional value" It means that something is nil. Try to find which one. You use various `!` which are yelling: "Crash if the value is nil". – Larme Jan 24 '18 at 14:51
  • I'm pretty sure serverTime must be nil and this is also the reason for the crash! – Jonas0000 Jan 24 '18 at 14:54
  • You should use https. Note that in Swift 3 or later you should drop NS prefix from NSDate, NSTimeZone and NSURL – Leo Dabus Jan 24 '18 at 14:54
  • 1
    I didn't run your code, but if `serverTime` is nil, and you do `serverTime as! NSDate`, that would cause a crash. Is your dateFormatter wrong? Do you mind printing `contentType` ? – Larme Jan 24 '18 at 14:55

2 Answers2

0

According to you, serverTime as! NSDate is reason for fatal error: So you may not be getting string date contentType in a date format set by you ("EEE, dd MMM yyyy HH:mm:ss z").

Set date formate of date formatter, matching with your contentType date.

What is result of contentType?

Try this and let me know date string

if let contentType = httpResponse!.allHeaderFields["Date"] as? String {

        print("contentType - \(contentType)") // What is result of contentType here?
        let dFormatter = DateFormatter()
        dFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
         // Update here - Use If-let block for NSDate casting and remove "as! NSDate" from completionHandler
        if let serverTime = dFormatter.date(from: contentType) as? NSDate {
           completionHandler(serverTime)
        }
}

Following answer may help you, how to handle and work with date formatter (It's in objective-c but help you):

Also, once look at this documents/links:

Edit: You date format is fine and working.

enter image description here

Krunal
  • 77,632
  • 48
  • 245
  • 261
0

After trying many times. I found the solution. Just add this line of code:

let Formatter = DateFormatter()
Formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale
Formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"

Enjoy!