跟踪通过我的应用发送和接收的数据的使用情况

如何跟踪通过我的应用程序发送和接收的数据的使用情况?

我只是想logging我的应用程序运行时发送和接收的字节。 如果我可以分别获得Wifi和蜂窝networking的信息,那么这将是伟大的,但它不是一个优先事项。

我知道如何find设备的总使用率 – https://stackoverflow.com/a/8014012/427969

此外,我知道我可以使用仪器来收集networking活动数据,但我想logging这些数据在我的应用程序,所以需要一个编程方式来做到这一点。

我试图search这个,但我发现是设备的networking使用情况,而不是一个特定的应用程序的使用情况。

以下是Whatsapp的设置 – >使用情况页面的屏幕截图,可以更好地了解我正在尝试做什么:

在这里输入图像说明

我正在使用AFNetworking的HTTP请求和响应如下:

 NSData* requestData = [NSJSONSerialization dataWithJSONObject:info options: NSJSONWritingPrettyPrinted error:&error]; if(error != nil) { NSLog(@"Error: converting JSON: %@, %@", error, error.userInfo); } [request setHTTPMethod:@"POST"]; [request setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"]; [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"]; [request setHTTPBody: requestData]; /* ################### ----------------- ################### WILL [requestData length] BE THE NUMBER OF BYTES SEND ??? ################### ----------------- ################### */ NSLog(@"data bytes: %d", [requestData length]); NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL .....]; AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest: request success: ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { } failure: ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { }]; [operation start]; 

我已经更新了我的问题。

有人可以回答: [requestData length]是一个请求的字节数SEND吗?

有几种方法取决于您使用哪种类下载AFNetworking

AFHTTPRequestOperation例如有以下方法:

 setDownloadProgressBlock:^(NSInteger bytesRead, NSInteger totalBytesRead, NSInteger totalBytesExpectedToRead) 

相反,有一个这样的方法:

 setUploadProgressBlock:^(NSInteger bytesWritten,long long totalBytesWritten,long long totalBytesExpectedToWrite) 

有了这个方法,你应该尝试跟踪所有你上传和下载的数据。

AFJSONRequestOperationAFJSONRequestOperation的子类,所以这些方法应该在任何一个类中工作。

请注意,只发送一个“json请求”到networking服务器并不意味着你没有下载。 当然,你必须得到的内容 – json – 这将是你的数据下载。

此外,你问问是否[requestData length]告诉你正确的大小发送到服务器。 这不是确切的大小,因为在你的请求数据中,你没有额外的HTTP请求头,所以你的大小会比原来发送的字节小一些。

每次执行上述方法之一时,都应该添加字节读取的结果,并将其添加到在执行此方法之前读取的字节中。 当然,你必须将当前的bytesRead永久地保存在coredata中,或者任何其他的持久化存储。

我使用亚历山大提到的方法如下:

 AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest: request]; [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { // success } failure:^(AFHTTPRequestOperation *operation, NSError *error) { // failure }]; [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) { // bytes received - saved bytesRead variable to NSUserDefaults }]; [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) { // bytes sent - saved bytesWritten variable to NSUserDefaults }]; [operation start];