I am trying to calculate network speed in my app, so I can upload only that much of data which can be uploaded in such network conditions. For that what my plan is:
- My App will have a default speed may be (500KB/s).
- My app will send request which have 500kb of data.
- It will monitor round trip time taken by system to upload data and get response. e.g App received 200kb data in 5 seconds than speed will be (500+200)/5.
- According to above example my bandwidth is 140KB/s for that request.
- I'll be calculating exponential moving average from my bandwidth.
- I'll send next request based on the calculated average bandwidth.
Here is my implementation for NSURLSession:
//Initializing NSURLSession [one time only]
let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("com.test.ios.background")
self.backgroundSession = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
// Create session task:
var urlSessionTask = self.backgroundSession.uploadTaskWithRequest(request, fromFile: NSURL.fileURLWithPath(filePath!)) urlSessionTask.resume()
let requestStartTime = NSDate().timeIntervalSinceReferenceDate
//On didCompleteWithError calculating speed.
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
let downloadEndTime = NSDate().timeIntervalSinceReferenceDate
let networkSpeed = Int(Double(sessionTask.receivedData.length + task.countOfBytesSent) / (downloadEndTime - requestStartTime))
}
If I loose bandwidth I can find it using this approach, as my average get down, but the problem is once I reached to low bandwidth and than my network conditions get improved, my bandwidth won't get improved because I am keep sending less data in request and it will keep saying that bandwidth is low.
Is there any way by which I can find if my network condition are improved and I can send more data?
One solution in my mind is, I can send max data (may be 500KB) in every 10th request, so at that time I can get higher bandwidth in network conditions are improved.