Search code examples
iosobjective-cios7xcode6

how to get the download time of a video from server in device in milliseconds in iOS


I have video on my server and i want to know in how much time my video requires to download from server in the device. So that i can calculate the download time and check if server is slow or not. Any help would be appreciated.

Here is my code:

  NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:[[Configuration sharedInstance] fatchTimeOut]];

  [GMURLConnection sendAsynchronousRequest:request queue:self.operationQueue type:type withSubType:subType completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

 //**********************Success Handling ********************
    if (type == OperationTypeMeta) {
        failCount = 0;
        NSError *error = nil;

        NSArray *serverResponse=[NSArray array];
        if(data)
            serverResponse = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
       }];

Solution

  • You cannot use sendAsynchronousRequest and monitor connection status. As per apple docs:

    To retrieve the contents of a URL using a completion handler block: If you do not need to monitor the status of a request, but merely need to perform some operation when the data has been fully received, you can call sendAsynchronousRequest:queue:completionHandler:, passing a block to handle the results.

    So you have to implement NSURLConnection delegate. If you like block style(as I really really do), just create new class which implement delegate methods and takes NSURLRequest, status block and completion block as params and call them in appropriate delegate methods. This way you will have block-styled asynchronous requests with status updates.

    If you do not know how to measure remaining time - each time didReceiveData: method is called append data length to class variable, and calculate how much time passed since last method receive. This way you have velocity(bytes per second). Knowing how big is your downloaded file just divide remaining size to your velocity and you'll get remaining time. There are some neat algoritms out there to get neat/steady remaining time instead of just jumping from 30secs to 2 mins(if we assume our internet connection is tricky). I've personally used @Ben Dolman's solution posted over here:

    averageSpeed = SMOOTHING_FACTOR * lastSpeed + (1-SMOOTHING_FACTOR) * averageSpeed;
    

    With some tweaking and playing with SMOOTHING_FACTOR I've accomplished great results.