快速获取服务器时间 [英] Swift get server time
问题描述
有没有一种方法可以让服务器快速使用时间.我想基于服务器设置静态时间.这样,即使用户更改了时区和日期,也没有关系,并且显示在视图控制器上的时间将是基于服务器而不是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)
目前上面的代码,如果更改了电话设置,则更改日期和时间.我也在我的代码中使用解析.有没有一种方法可以从解析中获取服务器时间.
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()
}
这篇关于快速获取服务器时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!