如何使用Swift检查网络速度 [英] How to check the network speed using swift
本文介绍了如何使用Swift检查网络速度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Google上搜索了太多页面,说到网络的可访问性(只有是或否),但是我从未听说有人可以使用Swift xcode环境检测网络速度.我需要此功能(检测到某些主机的网络速度),有人可以为我提供有关此问题的线索
I have googled too many pages saying on the network reachability (only yes or no availibilty), but I never heard somebody could detect the network speed using Swift xcode environment. I need this feature(detect the network speed to some host), could someone gave me a clue on this issue
推荐答案
我使用此功能来计算 Swift 3 中的网络速度. 我从服务器下载图像并计算经过时间.
I made this func to calculate the network speed in Swift 3. I download an image from my server and calculate the elapsed time.
func testSpeed() {
let url = URL(string: "http://my_image_on_web_server.jpg")
let request = URLRequest(url: url!)
let session = URLSession.shared
let startTime = Date()
let task = session.dataTask(with: request) { (data, resp, error) in
guard error == nil && data != nil else{
print("connection error or data is nill")
return
}
guard resp != nil else{
print("respons is nill")
return
}
let length = CGFloat( (resp?.expectedContentLength)!) / 1000000.0
print(length)
let elapsed = CGFloat( Date().timeIntervalSince(startTime))
print("elapsed: \(elapsed)")
print("Speed: \(length/elapsed) Mb/sec")
}
task.resume()
}
这篇关于如何使用Swift检查网络速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文