我目前正在开发一个应用程序,该应用程序根据文件下载的速度确定用户的互联网速度连接。
我发现了一个类似的问题,@Rob 在 Swift 中提供了答案:在 iOS 8 中确定互联网速度的正确方法
目前我正在使用 Swift 3,并尝试将他的代码从旧的 Swift 转换如下:
var startTime: CFAbsoluteTime!
var stopTime: CFAbsoluteTime!
var bytesReceived: Int!
var speedTestCompletionHandler: ((_ megabytesPerSecond: Double?, _ error: NSError?) -> ())!
func testDownloadSpeedWithTimout(timeout: TimeInterval, completionHandler:@escaping (_ megabytesPerSecond: Double?, _ error: NSError?) -> ())
{
let url = URL(string: "http://www.someurl.com/file")!
startTime = CFAbsoluteTimeGetCurrent()
stopTime = startTime
bytesReceived = 0
speedTestCompletionHandler = completionHandler
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForResource = timeout
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
session.dataTask(with: url).resume()
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)
{
bytesReceived! += data.count
stopTime = CFAbsoluteTimeGetCurrent()
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
{
let elapsed = stopTime - startTime
guard elapsed != 0 && (error == nil || (error?.domain == NSURLErrorDomain && error?.code == NSURLErrorTimedOut)) else {
speedTestCompletionHandler(megabytesPerSecond: nil, error: error)
return
}
let speed = elapsed != 0 ? Double(bytesReceived) / elapsed / 1024.0 / 1024.0 : -1
speedTestCompletionHandler(megabytesPerSecond: speed, error: nil)
}
我设法转换了大部分代码,但似乎遇到了一些错误2:
有人可以提供帮助吗?谢谢