Search code examples
iosafnetworking

How to set download status of UIProgressView in UILabel using AFNetworking?


Here is my code how to show progress bar when using AFNetworking and it works perfectly.

Now, my question is I want to set downloading status of progress view in label (like inetger value 45% and when completed then status is completed), then how can I archive this using AFNetworking ? **

EDITED : In below code it saves image in document directory, but its taking "Suggested name" for file, not custom name. Now my question is when image save to completely in document directory I have path of it, how can I display that image in image view using that path ? If anyone know, please help me.

**

#import "ViewController.h"
#import "AFNetworking/AFNetworking.h"
#import "UIKit+AFNetworking/UIKit+AFNetworking.h"

#define URL @"https://secure.static.tumblr.com/6f8f2414ccc2def5e14e54b485dc07b5/8z4dq98/m0pn2d66g/tumblr_static_644cca222811a9dd32a6ecba52dfa1172.jpg"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

}

- (IBAction)ActionPerform:(UIButton *)sender
{

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

    NSURL *strURL = [NSURL URLWithString:URL];
    NSURLRequest *request = [NSURLRequest requestWithURL:strURL];

    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response)
         {

                NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];


                return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
        } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error)
        {
             NSLog(@"File downloaded to: %@", filePath);
        }];

    [self.ProgressView setProgressWithDownloadProgressOfTask:downloadTask animated:YES];
    [downloadTask resume];
}
@end

here is complete answer :

#import "ViewController.h"
#import "secondViewController.h"

#define URL @"https://upload.wikimedia.org/wikipedia/commons/e/ec/USA-NYC-American_Museum_of_Natural_History.JPG"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.progressBar.hidden = YES ;
    self.lblProgressStatus.hidden = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)Action:(UIButton *)sender
{
    self.progressBar.hidden = NO ;
    self.lblProgressStatus.hidden = NO ;
    self.ActionDownload.enabled = NO ;

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

    NSURL *strURL = [NSURL URLWithString:URL];
    NSURLRequest *request = [NSURLRequest requestWithURL:strURL];

    NSProgress *progress;

    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response)
        {
                NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
                return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
        }
        completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error)
        {
                [self.progressBar setHidden:YES];
                self.lblProgressStatus.text = @"Download completed" ;
                NSLog(@"File downloaded to: %@", filePath);

                NSString * strTemp = [NSString stringWithFormat:@"%@", filePath];
                NSArray *components = [strTemp componentsSeparatedByString:@"/"];
                id obj = [components lastObject];
                NSLog(@"%@", obj);

            NSString *docPath = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
            NSString *strFilePath = [NSString stringWithFormat:@"%@/%@",docPath, obj];

            BOOL fileExists=[[NSFileManager defaultManager] fileExistsAtPath:strFilePath];

            if (!fileExists)
            {
                NSLog(@"File Not Found");
            }
            else
            {
                UIImage * image = [UIImage imageWithContentsOfFile:strFilePath];
                self.imageView.image = image ;
            }
            [progress removeObserver:self forKeyPath:@"fractionCompleted" context:NULL];

        }];

    [self.progressBar setProgressWithDownloadProgressOfTask:downloadTask animated:YES];
    [downloadTask resume];

    [progress addObserver:self
               forKeyPath:NSStringFromSelector(@selector(fractionCompleted))                  options:NSKeyValueObservingOptionNew
                  context:NULL];

}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"fractionCompleted"])
    {
        NSProgress *progress = (NSProgress *)object;
        int temp = progress.fractionCompleted * 100 ;
       // NSLog(@"%d", temp);
       NSString * strTemp = @"%";

        dispatch_async(dispatch_get_main_queue(), ^{
            // Update the UI
            self.lblProgressStatus.text = [NSString stringWithFormat:@"%d %@", temp, strTemp];
        });
    }
    else
    {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
@end

Solution

  • For more detail see https://stackoverflow.com/a/19380812/5235106

    Here is the answer

    - (IBAction)ActionPerform:(UIButton *)sender
    {    
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];    
        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];    
        NSURL *strURL = [NSURL URLWithString:URL];
        NSURLRequest *request = [NSURLRequest requestWithURL:strURL];    
        NSProgress *progress;
        NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response)
             {    
                    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];    
                    return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
            } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error)
            {
                 NSLog(@"File downloaded to: %@", filePath);
            }];    
        [self.ProgressView setProgressWithDownloadProgressOfTask:downloadTask animated:YES];
        [downloadTask resume];
        [progress addObserver:self
            forKeyPath:@"fractionCompleted"
               options:NSKeyValueObservingOptionNew
               context:NULL];
    }
    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
    {
        if ([keyPath isEqualToString:@"fractionCompleted"]) {
            NSProgress *progress = (NSProgress *)object;
            // update the label text use progress
        } else {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
    @end