使用 NSOperationQueue 跟踪下载



我有一个有 5 NSOperations的队列。队列的setMaxConcurrentOperationCount设置为 1。每个操作基本上都是对服务器下载特定文件的调用。

仅当文件保存到磁盘时,跟踪一个文件的下载是否已完成以启动另一个NSOperation的最佳方法是什么?或者有没有办法让NSOperations知道文件的下载进度?

您可以简单地子类NSOperation并将用于下载数据并将其保存到文件系统的代码放入NSOperation子类的-main方法中 操作完成后,NSOperationQueue中的下一个操作将自动开始执行

@implementation MyOperation
- (void) main {
    if ([self isCancelled]) {
        NSLog(@"** operation cancelled **");
    } else {
        NSURL *conUrl = [NSURL URLWithString: urlString];
        NSError *error;
        NSData *conData = [NSData dataWithContentsOfURL: conUrl options: NSDataReadingMappedIfSafe error: & error];
        if (!error) {
            UIImage *image = [
                [UIImage alloc] initWithData: conData];
            NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex: 0];
            NSString *jpgFilePath = [NSString stringWithFormat: @"%@/%@.jpg", cacheDir, textLabel];
            conData = [NSData dataWithData: UIImageJPEGRepresentation(image, 1.0f)];
            [conData writeToFile: jpgFilePath atomically: YES];
        }
    }
    NSLog(@"Operation finished");
}

@end
您应该

重写NSOperation子类中的isFinished方法,以便仅在实际完成时才返回YES

最新更新