Right way of determining internet speed in iOS 8

后端 未结 2 1893
-上瘾入骨i
-上瘾入骨i 2020-11-29 06:05

I am following the below code which I copied and converted from a stack overflow question.

I am getting internet speed however I am not sure, If I am doing right thi

相关标签:
2条回答
  • 2020-11-29 06:42

    You code snippet was taken from this answer. I've updated it to use NSURLSession. The Swift rendition is below:

    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 讨论(0)
  • 2020-11-29 06:55

    Here is the updated code in Swift 4.0

    class SpeedTest: UIViewController, URLSessionDelegate, URLSessionDataDelegate {
    
    
        typealias speedTestCompletionHandler = (_ megabytesPerSecond: Double? , _ error: Error?) -> Void
    
        var speedTestCompletionBlock : speedTestCompletionHandler?
    
        var startTime: CFAbsoluteTime!
        var stopTime: CFAbsoluteTime!
        var bytesReceived: Int!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
    
            checkForSpeedTest()
    
        }
    
        func checkForSpeedTest() {
    
            testDownloadSpeedWithTimout(timeout: 5.0) { (speed, error) in
                print("Download Speed:", speed ?? "NA")
                print("Speed Test Error:", error ?? "NA")
            }
    
        }
    
        func testDownloadSpeedWithTimout(timeout: TimeInterval, withCompletionBlock: @escaping speedTestCompletionHandler) {
    
            guard let url = URL(string: "https://images.apple.com/v/imac-with-retina/a/images/overview/5k_image.jpg") else { return }
    
            startTime = CFAbsoluteTimeGetCurrent()
            stopTime = startTime
            bytesReceived = 0
    
            speedTestCompletionBlock = withCompletionBlock
    
            let configuration = URLSessionConfiguration.ephemeral
            configuration.timeoutIntervalForResource = timeout
            let session = URLSession.init(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
    
            if let aTempError = error as NSError?, aTempError.domain != NSURLErrorDomain && aTempError.code != NSURLErrorTimedOut && elapsed == 0  {
                speedTestCompletionBlock?(nil, error)
                return
            }
    
            let speed = elapsed != 0 ? Double(bytesReceived) / elapsed / 1024.0 / 1024.0 : -1
            speedTestCompletionBlock?(speed, nil)
    
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题