我的应用程序要求用户处于联机状态,并且即使用户更改了日期,也正在尝试获取服务器时间。我找到了此代码,并且仅在我第一次运行该应用程序时有效。然后下一次冻结,我必须更改网站。每次我更改网站时,它都会得到日期和时间,之后我会一直保持相同的准确时间。
代码:
CustomLocation
答案 0 :(得分:0)
使用NTP服务器还是更好,但是请尝试使用以下内容,这将忽略缓存:
func getTimeFromServer(completionHandler:@escaping (_ getResDate: Date?) -> Void){
let url = URL(string: "https://www.apple.com")
let urlRequest = URLRequest(url: url!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 20)
let task = URLSession.shared.dataTask(with: urlRequest) {(data, response, error) in
let httpResponse = response as? HTTPURLResponse
if let contentType = httpResponse!.allHeaderFields["Date"] as? String {
//print(httpResponse)
let dFormatter = DateFormatter()
dFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
let serverTime = dFormatter.date(from: contentType)
completionHandler(serverTime)
}
}
task.resume()
}