2016-09-23 80 views
1

我想使用此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) 
    } 

} 

回答

0

底部函数是URLSession完成下载时的代理回调。速度计算是在该函数的第二最后一行完成:

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

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