1

My application is continuously communicating with server and I want to calculate the bandwidth I am getting. For that I decided to calculate upload and download speed.

I am using NSURLSession to communicate with my server. What I am doing is: Storing timestamp when I resume my session task (eg. Time1). In URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) method when totalBytesSetnt exceeds or equals expecetedBytesToSent I get difference from Time1 to current time and this way I calculate upload speed.

Here is my code:

//Initializing NSURLSession
let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("com.test.ios.background")
var backgroundSession = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)

// Create session task:
var urlSessionTask = self.backgroundSession.uploadTaskWithRequest(request, fromFile: NSURL.fileURLWithPath(filePath!))
urlSessionTask.resume()
let time1 = NSDate().timeIntervalSinceReferenceDate

Here I captured time1 immediately after resuming session task.

func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
    if totalBytesSent >= totalBytesExpectedToSend {
        let time2 = NSDate().timeIntervalSinceReferenceDate
        let uploadSpeed = Int(Double(totalBytesSent) / (time2 - time1))            
    }
}

I am using this upload speed further in my code. I am sending same JSON data every time with new session task (as mentioned above). The problem is: On first request session take some time to upload the data, but after that it take too less time no matter in which network speed I am. (Using network link conditioner to change network).

Here are the samples:

1st Request: Bytes uploaded: 11492 in 1.62111800909042 seconds 
2nd Request: Bytes uploaded: 11492 in 0.00142198801040649 seconds 
3rd Request: Bytes uploaded: 11492 in 0.00102704763412476 seconds 
4th Request: Bytes uploaded: 11492 in 0.00102400779724121 seconds
Kapil Choubisa
  • 5,152
  • 9
  • 65
  • 100

0 Answers0