swift簡單實現測試網速
阿新 • • 發佈:2021-02-06
技術標籤:swift
程式碼如下
import Foundation
class SpeedTestig{
func NetSpeedTesting(){
let url = URL(string: "https://images.apple.com/v/imac-with-retina/a/images/overview/5k_image.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("error or nil")
return
}
guard resp != nil else{
print("rsponse is nil")
return
}
let length = Float((resp?.expectedContentLength)!) / 1048576.0 * 8 // 1024 * 1024 = 1048576 * 8 為單位轉為bit 單位Mbps
print(length)
let elapsed = Float(Date().timeIntervalSince(startTime))
print(elapsed)
print(length/elapsed)
}
task.resume()
}
}
測試三次,結果如下,和測速網結果基本相符
轉自https://stackoverflow.com/questions/38635804/how-to-check-the-network-speed-using-swift
稍作改動
如有侵權,告知立刪