首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在iOS中使用afnetworking下载图像进度条

在iOS中使用afnetworking下载图像进度条
EN

Stack Overflow用户
提问于 2018-03-21 06:38:50
回答 1查看 520关注 0票数 1

我目前正在使用afnetworking下载图像,但是进度条在第一次不是平滑的,但是当我第二次运行这个代码时,进度条是平滑的,这是我下载图像的代码。

进度条的工作方式是向上,向下,而不是平滑,但当我第二次运行代码时,它运行得很平稳。

代码语言:javascript
复制
  progressBar.progress = 0.0;

self.imageDownloads=[[NSMutableArray alloc]init];

[self.imageDownloads addObject:[[ImageDownload alloc] initWithURL:[NSURL URLWithString:@""]];

 for (int i=0; i < self.imageDownloads.count; i++)
{
    ImageDownload *imageDownload = self.imageDownloads[i];
    imageDownload.filename = [NSString stringWithFormat:@"MyImage%d",i];
    [self downloadImageFromURL:imageDownload];
}

Here is my code to download images




- (void)downloadImageFromURL:(ImageDownload *)imageDownload
{

 NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [docsPath stringByAppendingPathComponent:imageDownload.filename];
NSURLRequest *request = [NSURLRequest requestWithURL:imageDownload.url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
    imageDownload.totalBytesRead = totalBytesRead;
    imageDownload.totalBytesExpected = totalBytesExpectedToRead;
    [self updateProgressView];
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSAssert([responseObject isKindOfClass:[NSData class]], @"expected NSData");
    NSData *responseData = responseObject;
    [responseData writeToFile:filePath atomically:YES];

    // Because totalBytesExpected is not entirely reliable during the download,
    // now that we're done, let's retroactively say that total bytes expected
    // was the same as what we received.

    imageDownload.totalBytesExpected = imageDownload.totalBytesRead;
    [self updateProgressView];

    NSLog(@"finished %@", imageDownload.filename);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"error %@", imageDownload.filename);
}];
[operation start];

}

代码语言:javascript
复制
 - (void)updateProgressView
{
double totalTotalBytesRead = 0;
double totalTotalBytesExpected = 0;

for (ImageDownload *imageDownload in self.imageDownloads)
{
    // note,
    //    (a) totalBytesExpected is not always reliable;
    //    (b) sometimes it's not present at all, and is negative
    //
    // So, when estimating % complete, we'll have to fudge
    // it a little if we don't have total bytes expected

    if (imageDownload.totalBytesExpected >= 0)
    {
        totalTotalBytesRead += imageDownload.totalBytesRead;
        totalTotalBytesExpected += imageDownload.totalBytesExpected;
    }
    else
    {
        totalTotalBytesRead += imageDownload.totalBytesRead;
        totalTotalBytesExpected += (imageDownload.totalBytesRead > kDefaultImageSize ? imageDownload.totalBytesRead + kDefaultImageSize : kDefaultImageSize);
    }
}

if (totalTotalBytesExpected > 0)
    [progressBar setProgress:totalTotalBytesRead / totalTotalBytesExpected animated:YES];
else
    [progressBar setProgress:0.0 animated:NO];

}

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-21 19:07:12

这段代码来自2013年的一个答案。我建议

  • 不要使用不推荐的AFHTTPRequestOperation,而是使用基于NSURLSession下载任务的解决方案。如果您想要使用AFNetworking,那么他们就有一种机制来做到这一点。
  • 不要自己更新/计算百分比,而是现在使用NSProgress进行单个下载,这些下载是某些父NSProgress的子类。您可以让您的UIProgressView观察到这一点。最终的结果是,您只需更新子NSProgress实例,而父视图的进度视图就会自动更新。

例如,假设我有一个名为UIProgressView的父totalProgressView,而我有一个它正在观察的NSProgress

代码语言:javascript
复制
@interface ViewController () <UITableViewDataSource>

@property (nonatomic, strong) NSProgress *totalProgress;
@property (nonatomic, strong) NSMutableArray <ImageDownload *> *imageDownloads;

@property (nonatomic, weak) IBOutlet UIProgressView *totalProgressView;
@property (nonatomic, weak) IBOutlet UITableView *tableView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.totalProgress = [[NSProgress alloc] init];
    self.totalProgressView.observedProgress = self.totalProgress;
    self.tableView.estimatedRowHeight = 50;
    self.tableView.rowHeight = UITableViewAutomaticDimension;

    self.imageDownloads = [NSMutableArray array];
}

...

@end

然后开始下载,创建一系列图像下载,将它们各自的NSProgress实例添加为上述totalProgress的子实例。

代码语言:javascript
复制
- (IBAction)didTapStartDownloadsButton {
    NSArray <NSString *> *urlStrings = ...

    NSURL *caches = [[[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:true error:nil] URLByAppendingPathComponent:@"images"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    self.totalProgress.totalUnitCount = urlStrings.count;
    for (NSInteger i = 0; i < urlStrings.count; i++) {
        NSURL *url = [NSURL URLWithString:urlStrings[i]];
        NSString *filename = [NSString stringWithFormat:@"image%ld.%@", (long)i, url.pathExtension];
        ImageDownload *imageDownload = [[ImageDownload alloc] initWithURL:url filename:filename];
        [self.imageDownloads addObject:imageDownload];
        [self.totalProgress addChild:imageDownload.progress withPendingUnitCount:1];

        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
            [imageDownload updateProgressForTotalBytesWritten:downloadProgress.completedUnitCount
                                    totalBytesExpectedToWrite:downloadProgress.totalUnitCount];
        } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
            return [caches URLByAppendingPathComponent:filename];
        } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
            //do whatever you want here
        }];
        [task resume];
    }

    [self.tableView reloadData];
}

哪里

代码语言:javascript
复制
//  ImageDownload.h

@import Foundation;

NS_ASSUME_NONNULL_BEGIN

@interface ImageDownload : NSObject

@property (nonatomic, strong) NSURL *url;
@property (nonatomic, strong) NSString *filename;
@property (nonatomic) NSProgress *progress;
@property (nonatomic) NSUInteger taskIdentifier;

- (id)initWithURL:(NSURL *)url
         filename:(NSString * _Nullable)filename;

/**
 Update NSProgress.

 @param totalBytesWritten Total number of bytes received thus far.
 @param totalBytesExpectedToWrite Total number of bytes expected (may be -1 if unknown).
 */

- (void)updateProgressForTotalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite;

@end

NS_ASSUME_NONNULL_END

代码语言:javascript
复制
static const long long kDefaultImageSize = 1000000; // what should we assume for totalBytesExpected if server doesn't provide it

@implementation ImageDownload

- (id)initWithURL:(NSURL *)url filename:(NSString *)filename {
    self = [super init];
    if (self) {
        _url = url;
        _progress = [NSProgress progressWithTotalUnitCount:kDefaultImageSize];
        _filename = filename ?: url.lastPathComponent;
    }
    return self;
}

- (void)updateProgressForTotalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    int64_t totalUnitCount = totalBytesExpectedToWrite;

    if (totalBytesExpectedToWrite < totalBytesWritten) {
        if (totalBytesWritten <= 0) {
            totalUnitCount = kDefaultImageSize;
        } else {
            double written = (double)totalBytesWritten;
            double percent = tanh(written / (double)kDefaultImageSize);
            totalUnitCount = written / percent;
        }
    }

    dispatch_async(dispatch_get_main_queue(), ^{
        self.progress.totalUnitCount = totalUnitCount;
        self.progress.completedUnitCount = totalBytesWritten;
    });
}

@end

为单个下载生成单个进度条,与totalProgress关联的进度条将自动为您更新,从而产生如下结果:

现在,很明显,您不需要孩子UIProgressView和父孩子,所以这取决于您。但我的想法是

  • 建立NSProgress的层次结构;
  • UIProgressView观察你想要的任何NSProgress;以及
  • 只需下载更新子NSProgress值,其余的就会自动发生。
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49399784

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档