【问题标题】:Swift download speed explanation迅捷下载速度说明
【发布时间】:2017-02-26 03:45:29
【问题描述】:

我想使用这个question 的代码答案,因为它正是我正在寻找的。但是我不能使用我不太了解的东西。

谁能解释一下这段代码是如何计算下载速度的?

class ViewController: UIViewController, NSURLSessionDelegate, NSURLSessionDataDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        testDownloadSpeedWithTimout(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: NSTimeInterval, completionHandler:(megabytesPerSecond: Double?, error: NSError?) -> ()) {
        let url = NSURL(string: "http://insert.your.site.here/yourfile")!

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

        let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
        configuration.timeoutIntervalForResource = timeout
        let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
        session.dataTaskWithURL(url).resume()
    }

    func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
        bytesReceived! += data.length
        stopTime = CFAbsoluteTimeGetCurrent()
    }

    func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
        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)
    }

}

【问题讨论】:

    标签: ios swift networking download


    【解决方案1】:

    底部函数是URLSession 完成下载时的委托回调。速度计算是在这个函数的倒数第二行完成的:

            let speed = elapsed != 0 ? Double(bytesReceived) / elapsed / 1024.0 / 1024.0 : -1
    

    这表示如果经过的时间不为 0,则将接收到的总字节数除以经过的秒数(这是通过将开始时间减去上面的 session: dataTask: didReceiveData: 委托方法时的时间来计算的)称为)。然后除以 1024.0 两次以从字节 -> 兆字节开始。否则,它返回 -1。

    【讨论】:

      猜你喜欢
      • 2015-03-12
      • 1970-01-01
      • 1970-01-01
      • 2019-05-30
      • 2011-06-09
      • 1970-01-01
      • 1970-01-01
      • 2011-05-23
      • 2021-09-14
      相关资源
      最近更新 更多