Getting downloads using AFNetworking 2.0 + NSProgress + Custom ProgressView

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]];
  //Return final path for podcast file

} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
if (!error) {
  //Handle success 
}
else{
  //Handle errors
}
}];


[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, .

+4
2

AFURLConnectionOperation -setDownloadProgressBlock:, totalBytesRead over totalBytesExpectedToRead .

, :

dispatch_async(dispatch_get_main_queue(), ^(void){
    //Run UI Updates
});
+11

Swift:

let progressView: UIProgressView?
let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
let sessionManager = AFURLSessionManager(sessionConfiguration: sessionConfiguration)
let request = NSURLRequest(URL: url)
let sessionDownloadTask = sessionManager.downloadTaskWithRequest(request, progress: nil, destination: { (url, response) -> NSURL in

            return destinationPath.URLByAppendingPathComponent(fileName) //this is destinationPath for downloaded file

            }, completionHandler: { response, url, error in

                //do sth when it finishes
        })

UIProgressView setProgressWithDownloadProgressOfTask:

progressView.setProgressWithDownloadProgressOfTask(sessionDownloadTask, animated: true)

sessionDownloadTask.resume()
+1

Source: https://habr.com/ru/post/1523902/


All Articles