Swift 获取服务器时间 [英] Swift get server time

查看:35
本文介绍了Swift 获取服务器时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法让服务器时间与 swift 一起使用.我想根据服务器设置静态时间.这样即使用户更改了时区和日期,也没关系,视图控制器上显示的时间将是基于服务器的时间而不是 NSDate

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 matter and the time which will show on the view controller will be a time based on the server rather than the NSDate

 let today = NSDate()
 println(today)

目前上面的代码,如果在手机设置中更改了日期和时间,则会更改日期和时间.我也在我的代码中使用了 parse.有没有办法从解析中获取服务器时间.

at present the above code, changes the date and time if its altered in the phone settings. i am also using parse in my code. is there a way to get the server time from parse.

推荐答案

基于此链接 https://github.com/freak4pc/NSDate-ServerDate 我为 swift 编写了代码.尝试和测试.它有效.

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()
}

这篇关于Swift 获取服务器时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆