我正在使用 NSURLConnection 与服务器执行 HTTP 通信。我希望找出我的应用程序发送/接收的确切字节数,包括 TCP/IP 开销。经过大量研究,还没有找到任何关于如何实现这一目标的有用信息。
如果使用它可以帮助我解决这个问题,我愿意切换到 CFStream。提前致谢。
我正在使用 NSURLConnection 与服务器执行 HTTP 通信。我希望找出我的应用程序发送/接收的确切字节数,包括 TCP/IP 开销。经过大量研究,还没有找到任何关于如何实现这一目标的有用信息。
如果使用它可以帮助我解决这个问题,我愿意切换到 CFStream。提前致谢。
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