Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

performance - How to check the network speed using swift

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...