簡體   English   中英

如何使用swift檢查網絡速度

[英]How to check the network speed using swift

我搜索了太多關於網絡可達性的頁面(只有是或不可用),但我從未聽說有人可以使用Swift xcode環境檢測網絡速度。 我需要這個功能(檢測一些主機的網絡速度),有人能給我一個關於這個問題的線索

我用這個函數來計算Swift 3中的網絡速度。 我從服務器下載圖像並計算經過的時間。

 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()


}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM