I got confused trying to make progress from the download task using AFNetworking 2.0. I created a singleton object where I centralized my download operations (my application will download podcast files).
So, I have a PodcastManager class with this method, where I also use the Podcast object I created:
- (void)downloadPodcast:(Podcast *)podcast completion:(CompletionBlock)completionBlock{
podcast.downloadState = DOWNLOADING;
NSURL *url = [NSURL URLWithString:podcast.enclosure];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSProgress *progress = [NSProgress progressWithTotalUnitCount:podcast.size];
NSURLSessionDownloadTask *downloadTask = [self.downloadManager downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *documentsDirectoryPath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
if (!error) {
}
else{
}
}];
[progress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:nil];
[downloadTask resume];
if (completionBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock();
});
}
}
Right now, for debugging purposes, I have this also in PodcastManager:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"fractionCompleted"] && [object isKindOfClass:[NSProgress class]]) {
NSProgress *progress = (NSProgress *)object;
NSLog(@"Download at %f", progress.fractionCompleted);
}
}
I call the downloadPodcast: completion: method from the UITableViewController, where each cell represents a Podcast. What I'm trying to do is show a custom run in a cell with the progress of loading this podcast.
, AFNetworking 2.0 UIProgressView, , https://github.com/danielamitay/DACircularProgress, : (
- ?
: , . KVO. AFURLSessionManager setDownloadTaskDidWriteDataBlock, , .
[[manager downloadManager] setDownloadTaskDidWriteDataBlock:^(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
self.downloadPercentage = (float)totalBytesWritten/(float)totalBytesExpectedToWrite;
}];
KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"downloadPercentage"] && [object isKindOfClass:[FDSEpisodeCell class]]) {
int percentage = self.downloadPercentage * 100;
NSLog(@"Percentage %d", percentage);
[self.downloadLabel setText:[NSString stringWithFormat:@"%d",percentage]];
}
}
, UILabel , , , . , ?. setNeedsDisplay, . reloadData TableView, - , .
, NSTimer, .