Swift get server time

后端 未结 3 436
野性不改
野性不改 2021-01-14 12:22

Is there a way to get a server time to use with swift. I want to set a static time based on a server. so that even if a user changes the time zone and the date, it wouldn\'t

3条回答
  •  北恋
    北恋 (楼主)
    2021-01-14 13:07

    You shouldn't make the same network call every time you need to get corrected datetime.

    So I would do like below, so I can call setSeverDate() only when I need to correct datetime:

    var serverDate = Date() {
        didSet {
            let possibleNow = Date()
            gap = possibleNow.distance(to: serverDate)
        }
    }
    var gap: TimeInterval = 0
    var correctedDate: Date {
        let possibleNow = Date()
    
        //Ignores network delay time same with or less than 2 seconds
        let now = abs(gap) > 2 ? possibleNow.advanced(by: gap) : possibleNow
    
        //For Debugging
        print("\(possibleNow) + \(gap) = \(now)")
    
        return now
    }
    
    func setServerDate() {
        let url = URL(string: "https://www.google.com")
    
        URLSession.shared.dataTask(with: url!) { _, response, _ in
            let httpResponse = response as? HTTPURLResponse
            if let contentType = httpResponse!.allHeaderFields["Date"] as? String {
                let formatter = DateFormatter()
                formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
                formatter.timeZone = TimeZone.current
                serverDate = formatter.date(from: contentType) ?? Date()
            } else {
                print("getting google server date failed")
                serverDate = Date()
            }
        }.resume()
    }
    

提交回复
热议问题