I'm using the code below snapped from this question Right way of determining internet speed in iOS 8 to make speed test in my app but when make a test and compare with the speed test tool http://www.speedtest.net/ the result of my app is less than the speedTest.net by half if my app speed result 1mbps the speedtest.net result is 2mbps or more
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?) -> ())!
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)
}
}