Chenglu
Chenglu

Reputation: 884

Alamofire 4/Swift: progress handler does not offer bytesRead and totalBytesRead anymore?

Recently, I am trying to migrate to Swift 3, which means I will also need to use Alamofire 4.

In Alamofire 3, the progress handler offers access to bytesRead, totalBytesRead, totalBytesExpectedToRead, however in Alamofire 4, it seems that the handler only has one argument "progress", which only allows me to see the "fractionCompleted". But I will need the bytesRead and totalBytesRead for UILabel's texts. I wonder is it possible for me to get these two values? Thanks a lot!

Modification:

Just had a look at the Progress class, and found that there are completedUnitCount, totalUnitCount, which seem to be the alternative for totalBytesRead and bytesRead. Not sure if I am on the right track?

Upvotes: 1

Views: 893

Answers (2)

pedrouan
pedrouan

Reputation: 12910

Exactly, totalUnitCount and completedUnitCount have the same meaning as totalBytesExpectedToRead vs. totalBytesRead. bytesRead was a value of an amount incremented (in each iteration) to the totalBytesRead value.

Now the added fractionCompleted is already a ratio in type of Double, so it is useful when used as a value for a progress bar, for example.

I've tested several Progress values so this is the code (tested on file about 600 kB in size):

.downloadProgress { progress in
     print("fractionCompleted: \(progress.fractionCompleted)")                
     print("completedUnit: \(progress.completedUnitCount)")
     print("totalUnitCount: \(progress.totalUnitCount)")
}

... outputs following (I've chosen first 3 iterations from the debug console):

fractionCompleted: 0.104675046718523 
completedUnit: 65536 
totalUnitCount: 626090

fractionCompleted: 0.209350093437046 
completedUnit: 131072 
totalUnitCount: 626090

fractionCompleted: 0.314025140155569 
completedUnit: 196608 
totalUnitCount: 626090

...

Upvotes: 4

alexburtnik
alexburtnik

Reputation: 7741

Yes, you can rely on completedUnitCount and totalUnitCount if you're doing a single download/upload task (without subtasks)

From Alamofire 4 doc:

If the receiver NSProgress object is a "leaf progress" (no children), then the fractionCompleted is generally completedUnitCount / totalUnitCount. If the receiver NSProgress has children, the fractionCompleted will reflect progress made in child objects in addition to its own completedUnitCount. As children finish, the completedUnitCount of the parent will be updated.

Upvotes: 0

Related Questions