8

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

evering7
  • 101
  • 1
  • 1
  • 3
  • By speed do you mean theoretical or real-world throughput? Just the local area network or the whole connection to a server? HTTP or some other protocol? –  Jul 28 '16 at 12:16
  • Possible duplicate of [Right way of determining internet speed in iOS 8](http://stackoverflow.com/questions/33887748/right-way-of-determining-internet-speed-in-ios-8) –  Jul 28 '16 at 12:22
  • Why I am eager for this feature? Because my app need to download some xml file from host, if the network is slow, the downloading would be very uncomfortable to users. So it would be fine to cancel downloading when the app in advance know that the speed is too slow – evering7 Jul 28 '16 at 12:25
  • I mean not the local area network speed, but the whole connection to a server. Thank you for your comments – evering7 Jul 28 '16 at 12:26
  • The link to a similar question should help you with this answer. –  Jul 28 '16 at 12:27
  • @ColGraff This ain't duplicate to http://stackoverflow.com/questions/33887748/right-way-of-determining-internet-speed-in-ios-8, how will you make him understand about there is no library you have to do it by writing a code. – Hasya Jul 28 '16 at 13:13

1 Answers1

13

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


}
Rob
  • 2,649
  • 3
  • 27
  • 34
  • 1
    I was looking for something to work in Swift 2 and with a few tweaks, this code worked perfectly, thanks!! – Brett Nov 02 '18 at 13:58
  • 1
    @Brett this code is fine but there is a vast difference between speediest.net and mentioned code. any suggestion Rob? – Bhavesh Lathigara Jun 29 '20 at 07:36