How can I get current UTC time from Firebase Server (or any other server for that matter) independent of time set in the device? Currently developing an iOS app using Firebase and Swift 4.
如何从Firebase Server(或任何其他服务器)获取当前UTC时间,而与设备中设置的时间无关?目前正在使用Firebase和Swift 4开发iOS应用。
Thanks!
1 个解决方案
#1
0
If you really want to get the current time from a server, you can do it like this: (I am using the Google's server)
如果你真的想从服务器获取当前时间,你可以这样做:(我正在使用谷歌的服务器)
override func viewDidLoad() {
super.viewDidLoad()
//call ServerTimeReturn function
serverTimeReturn { (getResDate) -> Void in
let dFormatter = DateFormatter()
dFormatter.dateStyle = .long
dFormatter.timeStyle = .long
dFormatter.timeZone = TimeZone(abbreviation: "UTC")
let dateGet = dFormatter.string(from: getResDate!)
print("Formatted Time : \(dateGet)")
}
}
func serverTimeReturn(completionHandler:@escaping (_ getResDate: Date?) -> Void){
let url = URL(string: "http://www.google.com")
let task = URLSession.shared.dataTask(with: 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"
let serverTime = dFormatter.date(from: contentType)
completionHandler(serverTime)
}
}
task.resume()
}
#1
0
If you really want to get the current time from a server, you can do it like this: (I am using the Google's server)
如果你真的想从服务器获取当前时间,你可以这样做:(我正在使用谷歌的服务器)
override func viewDidLoad() {
super.viewDidLoad()
//call ServerTimeReturn function
serverTimeReturn { (getResDate) -> Void in
let dFormatter = DateFormatter()
dFormatter.dateStyle = .long
dFormatter.timeStyle = .long
dFormatter.timeZone = TimeZone(abbreviation: "UTC")
let dateGet = dFormatter.string(from: getResDate!)
print("Formatted Time : \(dateGet)")
}
}
func serverTimeReturn(completionHandler:@escaping (_ getResDate: Date?) -> Void){
let url = URL(string: "http://www.google.com")
let task = URLSession.shared.dataTask(with: 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"
let serverTime = dFormatter.date(from: contentType)
completionHandler(serverTime)
}
}
task.resume()
}