Skip to content

Instantly share code, notes, and snippets.

@dkarbayev
Last active February 10, 2018 01:34
Show Gist options
  • Save dkarbayev/dba1945338bca18a780de36da41529ea to your computer and use it in GitHub Desktop.
Save dkarbayev/dba1945338bca18a780de36da41529ea to your computer and use it in GitHub Desktop.
Network Speed Test Playground
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil)
func testSpeed(completion: ((Float?) -> Void)?) {
guard let url = URL(string: "http://ipv4.download.thinkbroadband.com/5MB.zip") else {
completion?(nil)
return
}
let request = URLRequest(url: url)
let startTime = Date()
let task = URLSession.shared.dataTask(with: request) { (data, resp, error) in
guard error == nil && data != nil && resp != nil else {
completion?(nil)
return
}
guard let contentLength = data?.count else {
completion?(nil)
return
}
let length = Float(contentLength)
let elapsed = Float(Date().timeIntervalSince(startTime))
let speed = length / elapsed / (1024 * 1024) // MBps
completion?(speed)
}
task.resume()
}
testSpeed { speed in
if let speed = speed {
print("Network speed: \(speed) MBps")
} else {
print("Couldn't measure network speed")
}
PlaygroundPage.current.finishExecution()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment