Добавление дочернего прогресса для загрузки нескольких файлов

Я загружаю несколько файлов, используя AFNetworking 3.0 в своем проекте. Я хочу показать прогресс загрузки всех файлов. Я добавил каждый дочерний прогресс каждой загрузки файла в родительский прогресс. Но не работает, приложение вылетает. Я получаю сообщение об ошибке -

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '<DownloadManager: 0x7f92e2f6e130>: An -observeValueForKeyPath:ofObject:change:context: message was received but not handled.
Key path: fractionCompleted

Вот мой класс загрузки -

@interface DownloadManager ()

@property (nonatomic, strong) NSProgress *progress;
@property (nonatomic, strong) Settings *settings;
@property (nonatomic, strong) DocumentDirectory *documentDirectory;

@end


@implementation DownloadManager

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.progress = [NSProgress new];
        [self.progress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:NULL];
        self.settings = [Settings new];
        self.documentDirectory = [DocumentDirectory new];
    }

    return self;
}

- (void) dealloc {
    [self.progress removeObserver:self forKeyPath:@"fractionCompleted"];
}


//Download the file from remote server in the document directory as Zip format
- (void) downloadCarContents:(NSArray *)urlArray forContent:(NSArray *)contentArray {

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    self.progress.totalUnitCount =  urlArray.count;
    self.progress.completedUnitCount = 0;

    for (NSInteger i = 0; i < urlArray.count; i++) {

        NSString *destinationPath = [self.documentDirectory getDownloadContentPath:contentArray[i]];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlArray[i]]];

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

            return [NSURL fileURLWithPath:destinationPath];

        } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {


        }];

        NSProgress *childProgress = [manager downloadProgressForTask:task];
        [self.progress addChild:childProgress withPendingUnitCount:1];

        NSLog(@"Total downloaded : %f", self.progress.fractionCompleted * 100.0);

        [task resume];
    }
}

@end

person Nuibb    schedule 07.02.2016    source источник


Ответы (1)


Вы забыли реализовать метод observeValueForKeyPath:ofObject:change:context:.

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSString *, id> *)change
                       context:(void *)context {
    if ([keyPath isEqualToString:@"fractionCompleted"]) {
        // process value
    }
}
person rmaddy    schedule 07.02.2016
comment
О, это моя ошибка. Спасибо. - person Nuibb; 07.02.2016
comment
Еще один вопрос. Как я могу гарантировать, что в блоке завершенияHandler все содержимое успешно загружено? Мне нужна эта проверка в блоке completeHandler, но не в методеObservValueForKeyPath с проверкой завершения дробного значения 1.0? - person Nuibb; 03.03.2016