1

我目前正在开发一个应用程序,该应用程序根据文件下载的速度确定用户的互联网速度连接。

我发现了一个类似的问题,@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

在此处输入图像描述

有人可以提供帮助吗?谢谢

4

2 回答 2

2

你应该用这个替换你的代码:

class ViewController: UIViewController, URLSessionDelegate, URLSessionDataDelegate
{

override func viewDidLoad()
{
    super.viewDidLoad()

    testDownloadSpeedWithTimout(timeout: 5.0) { (megabytesPerSecond, error) -> () in
        print("\(megabytesPerSecond); \(error)")
    }
}

var startTime: CFAbsoluteTime!
var stopTime: CFAbsoluteTime!
var bytesReceived: Int!
var speedTestCompletionHandler: ((_ megabytesPerSecond: Double?, _ error: NSError?) -> ())!

/// Test speed of download
///
/// Test the speed of a connection by downloading some predetermined resource. Alternatively, you could add the
/// URL of what to use for testing the connection as a parameter to this method.
///
/// - parameter timeout:             The maximum amount of time for the request.
/// - parameter completionHandler:   The block to be called when the request finishes (or times out).
///                                  The error parameter to this closure indicates whether there was an error downloading
///                                  the resource (other than timeout).
///
/// - note:                          Note, the timeout parameter doesn't have to be enough to download the entire
///                                  resource, but rather just sufficiently long enough to measure the speed of the download.

func testDownloadSpeedWithTimout(timeout: TimeInterval, completionHandler:@escaping (_ megabytesPerSecond: Double?, _ error: NSError?) -> ()) {
    let url = NSURL(string: "http://www.someurl.com/file")!

    startTime = CFAbsoluteTimeGetCurrent()
    stopTime = startTime
    bytesReceived = 0
    speedTestCompletionHandler = completionHandler

    let configuration = URLSessionConfiguration.ephemeral
    configuration.timeoutIntervalForResource = timeout
    let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
    session.dataTask(with: url as 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! as NSError).domain == NSURLErrorDomain && error?._code == NSURLErrorTimedOut)) else{
        speedTestCompletionHandler(nil, error as? NSError)
        return
    }

    let speed = elapsed != 0 ? Double(bytesReceived) / elapsed / 1024.0 / 1024.0 : -1
    speedTestCompletionHandler(speed, error as? NSError)
}
}
于 2016-12-17T07:51:57.160 回答
0

错误 1

Error是 Swift 3 中的一个协议。它ErrorType来自 Swift 2。该属性domainNSError.

我不是 100% 确定函数中是否总是URLSessionTask通过 a ,但我认为是这样。您可以尝试转换为,看看它是否成功。NSErrordidCompleteWithErrorerrorNSError

错误 2 和 3

错误消息似乎误导了我。但是当我查看 的声明时speedTestCompletionHandler,我注意到你不能使用参数标签。_在函数参数前面意味着您必须省略参数标签。相反,您必须speedTestCompletionHandler()像这样调用:

speedTestCompletionHandler(nil, error)
...
speedTestCompletionHandler(speed, nil)
于 2016-12-17T08:00:30.033 回答