这个易于使用且轻量级的组件允许您按顺序组织操作,提供用于记录进度和完成的单一直观接口。它还通过 NSProgress 实例使整个复合操作的取消成为可能。
以下代码演示了如何将导出视频的操作(从 ALAssetsLibrary 导出)、将结果上传到远程服务器以及进行一些必要的清理组合成三个步骤的操作。假设有两个类: ExportVidoOperation
和 UploadVideoOperation
,它们继承自 DKOperation
。
import <DKCompoundOperation/DKCompoundOperation.h>
static NSInteger const kExportOperationProgressFraction = 30;
static NSInteger const kUploadOperationProgressFraction = 65;
static NSInteger const kCleanupOperationProgressFraction = 5;
<...>
@property (nonatomic, strong) NSOperationQueue *queue;
@property (nonatomic, weak) NSProgress *progress;
<...>
DKCompoundOperation *operation = [[DKCompoundOperation alloc] init];
[operation addOperationCreatedUsingBlock:^DKOperation *{
return [ExportVideoOperation operationWithVideoAssetURL:assetURL];
} progressFraction:kExportOperationProgressFraction];
[operation addOperationCreatedUsingBlock:^DKOperation *{
return [UploadVideoOperation operation];
} progressFraction:kUploadOperationProgressFraction];
[operation addOperationWithOperationBlock:^(DKOperation *operation) {
operation.progress.totalUnitCount = 150;
// Perform some cleanup operations
// updating operation.progress
operation.completeOperation(YES, nil);
} progressFraction:kCleanupOperationProgressFraction];
operation.completionBlock = ^(BOOL success, NSError *error) {
if (error) {
NSLog(@"Error occured: %@", error);
return;
}
self.completedLabel.hidden = NO;
};
self.progress = operation.progress;
[self.queue addCompoundOperation:operation];
您可以使用 KVO 来跟踪进度对象的变化。有关更多信息,请访问 NSProgress 类参考 和 键值观察指南。
DKCompoundOperation 通过 CocoaPods 提供。要安装它,只需将以下行添加到您的 Podfile 中
pod "DKCompoundOperation"
Daniil Konoplev, [email protected]
DKCompoundOperation 可在 MIT 许可下使用。更多信息请参阅 LICENSE 文件。