Elitecoder
Elitecoder

Reputation: 170

How to calculate number of bytes sent/received including TCP/IP overhead in an iOS HTTP Connection?

I am using NSURLConnection to perform HTTP Communication with a server. I wish to find out the exact number of bytes sent/received by my application including the TCP/IP overhead. Haven't found any useful info on how to achieve this after much research.

I am willing to switch to CFStream if using that will help me with this issue. Thanks in advance.

Upvotes: 3

Views: 1244

Answers (1)

mashdup
mashdup

Reputation: 875

In my .h of the controller I declare two vars:

NSMutableData *_data;
float downloadSize;

Also don't forget the delegates in the .h

@interface SomeViewController : UIViewController <NSURLConnectionDataDelegate, NSURLConnectionDelegate>

Then in my .m:

- (void)connection: (NSURLConnection*) connection didReceiveResponse: (NSHTTPURLResponse*) response
    {
        NSInteger statusCode_ = [response statusCode];
        if (statusCode_ == 200) {
            downloadSize = [response expectedContentLength];
        }
    }
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
        if(!_data) _data = [[NSMutableData data]init];
        [_data appendData:data];
        progressView.progress =  ((float) [_data length] / (float) downloadSize);
    }

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
          unsigned char byteBuffer[[_data length]];
          [_data getBytes:byteBuffer];
          [_data writeToFile:pdfPath atomically:YES];

    }

This is my controller to download a pdf file. But it could be anything really. When it has a response, it gets the expected length, then every time it receives data, it appends it to my mutable data and then compares it to the expected size.

Hope this helps :D

Upvotes: 4

Related Questions