0

I am trying to detect speed of my internet using NSURLConnection. What I do is, I start downloading a file, in delegates of NSURLConnection, I start a time and then when the download finishes, it gets the time frame as well as the data received and then I calculated to get the mb/sec using the below code.

        if (startTime != nil) {

        elapsed = NSDate().timeIntervalSinceDate(startTime)
         NSLog("\(length) -- \(elapsed)")
        var d =  (Double(length) / elapsed)
        var result = CGFloat( d/1024)
        result = result * 0.0078125
        result = result * 0.0009765625
        return result

    }

My question is why I am dividing 1024 here because If I don't do I get something is bits/bytes...

I am assuming I am getting seconds from NSDate().timeIntervalSinceDate(startTime) and bytes from Nsdata length

I think I am getting right value however I am not sure. Let me know why it's necessary to divide 1024!

halfer
  • 19,824
  • 17
  • 99
  • 186
Saty
  • 2,563
  • 3
  • 37
  • 88
  • One more thing I marked that when I tested, its showing right results in simulator however in original device, its showing less!! – Saty Nov 24 '15 at 10:46
  • BTW, that example used `NSURLConnection`, which is now deprecated. Use `NSURLSession` instead. In answer to your question about `timeIntervalSinceDate`, that returns a [`NSTimeInterval`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/index.html#//apple_ref/c/tdef/NSTimeInterval), which is measured in seconds. – Rob Nov 24 '15 at 22:43

1 Answers1

0

I was dividing by 1024 in the example you took this from simply because I think looking at bytes per second yields a number that is too large to make sense of (and it suggests a misleading degree of accuracy given the variability in that number).

By dividing by 1024, you get kilobytes per second. To get megabytes per second, you'd divide by 1024 * 1024. The 1024 in that original code sample was a mistake, as that would yield kilobytes per second.

So, use whatever measurement you want. Bytes per second, kilobytes per second, megabytes per second. Or you can multiply megabytes per second by 8 and get megabits per second (another common measure of speed). Just divide the bytes per second by the appropriate factor.

Community
  • 1
  • 1
Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • thanx for the help!!!I think I am getting it done. Do I have to use NSURLSession instead of NSURLConnection? as I am getting data – Saty Nov 25 '15 at 13:07
  • @Saty - `NSURLConnection` was officially deprecated as of iOS 9, so while you technically can use it, it's not a good idea. You should't be using `NSURLConnection` unless you absolutely have to (e.g., you're trying to support iOS versions that predate `NSURLSession`, i.e. iOS 6 or earlier). – Rob Nov 25 '15 at 17:05