When we write the download interface, we need to show the user how many kb are downloaded per second, this time we need to calculate the speed. As follows:
I use afnetworking to do the download, we take afhttprequestoperation to raise the column, Afhttprequestoperation has a method:
[HTML] view plain copy
- -(void) Setdownloadprogressblock: (void (^) (Nsuinteger bytesread, Long long totalbytesread, long long Totalbytesexpectedtoread)) block
This method reads the guide data and then passes the block callback. The calculation speed is done in this block.
You need to define a download object: Downtask. Downtask Required Attributes: Totalread (Data read in one second), speed (velocity), date (the time after the last second calculation). Note: Here one second is not a strict sense of a second, it may be more than a second, we calculate the average speed, so no error is too large.
[HTML]View Plain Copy
- Calculate the speed in one second
- Downtask.totalread + = Bytesread;
- Get current time
- NSDate *currentdate = [NSDate Date];
- The current time and the previous second time to compare, greater than or equal to one second to calculate
- if ([currentdate timeIntervalSinceDate:downTask.date] >= 1) {
- Time difference
- Double Time = [currentdate timeIntervalSinceDate:downTask.date];
- Calculation speed
- Long long speed = downtask.total/time;
- Turn the speed into KB or m
- Downtask.speed = [Downtask formatbytecount:speed];
- Maintain variables, calculate cleared zeros
- Downtask.totalread = 0.0;
- Maintain variables and record the time of this calculation
- Downtask.date = currentdate;
wherein, downtask.speed = [Downtask formatbytecount:speed]; is used to convert bytes into the KB or m we need. The specific implementation is as follows:
[HTML] view plain copy
- -(nsstring*) Formatbytecount: (Long long) size
- {
- return [Nsbytecountformatter stringfrombytecount:size countstyle:nsbytecountformattercountstylefile];
- }
This method is placed in the downtask of the downloaded object.
iOS development download file speed calculation