Swift get server time

后端 未结 3 447
野性不改
野性不改 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:15

    Based on this link https://github.com/freak4pc/NSDate-ServerDate i wrote the code for swift. Tried and tested. And it works.

    override func viewDidLoad() {
        super.viewDidLoad()
    
        //call ServerTimeReturn function
    
        serverTimeReturn { (getResDate) -> Void in
            var dFormatter = NSDateFormatter()
            dFormatter.dateStyle = NSDateFormatterStyle.LongStyle
            dFormatter.timeStyle = NSDateFormatterStyle.LongStyle
            dFormatter.timeZone = NSTimeZone(abbreviation: "GMT")
            var dateGet = dFormatter.stringFromDate(getResDate)
    
            println("Formatted Time : \(dateGet)")
        }
    
            }
    
        func serverTimeReturn(completionHandler:(getResDate: NSDate!) -> Void){
    
        let url = NSURL(string: "http://www.google.com")      
        let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
            let httpResponse = response as? NSHTTPURLResponse
            if let contentType = httpResponse!.allHeaderFields["Date"] as? String {
    
                var dFormatter = NSDateFormatter()
                dFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
                var serverTime = dFormatter.dateFromString(contentType)
                completionHandler(getResDate: serverTime)
            }
        }
    
        task.resume()
    }
    

提交回复
热议问题