2016-09-23 84 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。