如何使用 AFNetworking 在 UILabel 中设置 UIProgressView 的下载状态?

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

这是我的代码如何在使用 AFNetworking 时显示进度条,它运行得很好。

现在,我的问题是我想在标签中设置进度视图的下载状态(例如 inetger 值 45%,完成后状态为完成),那么我如何使用 AFNetworking 将其存档? **

已编辑: 在下面的代码中,它将图像保存在文档目录中,但它采用 "Suggested name" 作为文件,而不是自定义名称。现在我的问题是,当图像完全保存在文档目录中时,我有它的路径,如何使用该路径在图像视图中显示该图像? 有知道的帮帮我吧

**

#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

这里是完整的答案:

#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

有关详细信息,请参阅

答案在这里

- (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