使用NSOperation和NSURLSession封装一个串行下载器

本文介绍了使用NSOperation和NSURLSession来实现串行下载的需求.

为何要这样

iOS中使用NSURLSession的NSURLSessionDownloadTask进行下载: 对于NSURLSessionDownloadTask对象, 执行resume方法之后, 即开始下载任务. 而下载进度是通过NSURLSessionDelegate的对应方法进行更新. 这意味着在发起下载任务后, 实际的下载操作是异步执行的. 如果顺序发起多个下载任务(执行resume方法), 各个任务的下载情况完全是在NSURLSessionDelegate的回调方法中体现. 这样会出现几个问题:

  • 多任务同时下载: 在iOS上NSURLSession允许4个任务同时下载,在一些应用体验上其实不如单个顺序下载(如音乐下载, 相机AR素材包下载等, 与其多首歌曲同时下载, 不如优先下载完一首, 用户可以尽快使用).
  • 任务间有依赖关系: 如AR素材包本身下载完成之后, 还要依赖另外的一个配置文件(Config.zip)等下载完成, 则即使该AR素材包下载完成, 但依然无法使用, 不能置为已下载状态.
  • 优先级问题: 如有的任务的优先级比较高, 则需要做到优先下载.
  • 下载完成时间不确定: 如上的使用场景, 因AR素材包和依赖文件的下载完成顺序也不确定, 导致必须采用一些机制去触发全部下载完毕的后续操作(如通知等).
  • 下载超时: NSURLSessionDownloadTask对象执行resume后, 如果在指定时间内未能下载完毕会出现下载超时, 多个任务同时下载时容易出现.

目标

以上边讲的AR素材包的场景为例, 我们想要实现一个下载机制:

  • 顺序点击多个AR素材, 发起多个下载请求, 但优先下载一个素材包, 以便用户可以尽快体验效果.
  • 对于有依赖关系的素材包, 先下载其依赖的配置文件, 再下载素材包本身, 素材包本身的下载完成状态即是该AR整体的下载完成状态.

实现过程

综合以上的需求, 使用NSOperation来封装下载任务, 但需要监控其状态. 使用NSOperationQueue来管理这些下载任务.

NSOperation的使用

CSDownloadOperation继承自NSOperation, 不过对于其executing, finished, cancelled状态, 需要使用KVO监控.

因为KVO依赖于属性的setter方法, 而NSOperation的这三个属性是readonly的, 所以NSOperation在执行中的这些状态变化不会自动触发KVO, 而是需要我们额外做一些工作来手动触发KVO.

其实, 可以简单理解为给NSOperation的这三个属性自定义setter方法, 以便在其状态变化时触发KVO.

@interface CSDownloadOperation : NSOperation

@end

@interface CSDownloadOperation ()

// 因这些属性是readonly, 不会自动触发KVO. 需要手动触发KVO, 见setter方法.
@property (assign, nonatomic, getter = isExecuting)     BOOL executing;
@property (assign, nonatomic, getter = isFinished)      BOOL finished;
@property (assign, nonatomic, getter = isCancelled)     BOOL cancelled;

@end

@implementation CSDownloadOperation

@synthesize executing       = _executing;
@synthesize finished        = _finished;
@synthesize cancelled       = _cancelled;


- (void)setExecuting:(BOOL)executing
{
    [self willChangeValueForKey:@"isExecuting"];
    _executing = executing;
    [self didChangeValueForKey:@"isExecuting"];
}

- (void)setFinished:(BOOL)finished
{
    [self willChangeValueForKey:@"isFinished"];
    _finished = finished;
    [self didChangeValueForKey:@"isFinished"];
}

- (void)setCancelled:(BOOL)cancelled
{
    [self willChangeValueForKey:@"isCancelled"];
    _cancelled = cancelled;
    [self didChangeValueForKey:@"isCancelled"];
}

@end
复制代码

NSOperation执行时, 发起NSURLSessionDownloadTask的下载任务(执行resume方法), 然后等待该任务下载完成, 才去更新NSOperation的下载完成状态. 然后NSOperationQueue才能发起下一个任务的下载.

在初始化方法中, 构建好NSURLSessionDownloadTask对象, 及下载所需的一些配置等.

- (void)p_setupDownload {
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    self.urlSession = [NSURLSession sessionWithConfiguration:config
                                                    delegate:self
                                               delegateQueue:[NSOperationQueue mainQueue]];

    NSURL *url = [NSURL URLWithString:self.downloadItem.urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url
                                             cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                         timeoutInterval:kTimeoutIntervalDownloadOperation];
    self.downloadTask = [self.urlSession downloadTaskWithRequest:request];
    self.downloadTask.taskDescription = self.downloadItem.urlString;
}
复制代码

重写其start, main和cancel方法:

/**
 必须重写start方法.
 若不重写start, 则cancel掉一个op, 会导致queue一直卡住.
 */
- (void)start
{
//    NSLog(@"%s %@", __func__, self);

    // 必须设置finished为YES, 不然也会卡住
    if ([self p_checkCancelled]) {
        return;
    }

    self.executing  = YES;

    [self main];
}

- (void)main
{
    if ([self p_checkCancelled]) {
        return;
    }

    [self p_startDownload];

    while (self.executing) {
        if ([self p_checkCancelled]) {
            return;
        }
    }
}

- (void)cancel
{
    [super cancel];

    [self p_didCancel];
}

复制代码

在p_startDownload方法中发起下载:

- (void)p_startDownload
{
    [self.downloadTask resume];
}
复制代码

使用NSURLSessionDownloadDelegate来更新下载状态

实现该协议的回调方法, 更新下载进度, 下载完成时更新状态.

- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
    // xxx
    [self p_done];
    // xxx
}

/* Sent periodically to notify the delegate of download progress. */
- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    CGFloat progress = 1.0 * totalBytesWritten / totalBytesExpectedToWrite;
    // xxx
    // 更新下载进度等
    // xxx
}

- (void)p_done
{
//    NSLog(@"%s %@", __func__, self);

    [self.urlSession finishTasksAndInvalidate];
    self.urlSession = nil;

    self.executing  = NO;
    self.finished   = YES;
}
复制代码

使用NSOperationQueue来管理串行下载队列

NSOperation中发起下载之后, 并不会立即设置其finished为YES, 而是会有一个while循环, 一直等到NSURLSessionDownloadDelegate的回调方法执行, 才会更新其finished状态.

而NSOperationQueue的特点就是上一个NSOperation的finished状态未置为YES, 不会开始下一个NSOperation的执行.

设置优先级

对NSOperation的优先级进行设置即可.

CSDownloadOperationQueue *queue = [CSDownloadOperationQueue sharedInstance];
CSDownloadOperation *op = [[CSDownloadOperation alloc] initWithDownloadItem:downloadItem
                                                               onOperationQueue:queue];
op.downloadDelegate = self;

// AR背景的优先级提升
op.queuePriority = NSOperationQueuePriorityHigh;
复制代码

获取下载进度及下载完成状态

通过实现CSDownloadOperationQueueDelegate, 以观察者的身份来接收下载进度及下载完成状态.

// MARK: - CSDownloadOperationQueueDelegate

/**
 CSDownloadOperationQueueDelegate通知obsever来更新下载进度
 */
@protocol CSDownloadOperationQueueDelegate <NSObject>

@optional
- (void)CSDownloadOperationQueue:(CSDownloadOperationQueue *)operationQueue
               downloadOperation:(CSDownloadOperation *)operation
             downloadingProgress:(CGFloat)progress;

- (void)CSDownloadOperationQueue:(CSDownloadOperationQueue *)operationQueue
               downloadOperation:(CSDownloadOperation *)operation
                downloadFinished:(BOOL)isSuccessful;

@end
复制代码

注意这里观察者模式的使用: observer为继承delegate的对象, 内存管理语义当然为weak.

// MARK: - observer

/**
 use observer to notify the downloading progress and result
 */
- (void)addObserver:(id<CSDownloadOperationQueueDelegate>)observer;
- (void)removeObserver:(id<CSDownloadOperationQueueDelegate>)observer;
复制代码

所以, 需要使用NSValue的nonretainedObjectValue. 除此之外, 可以使用NSPointerArray来实现弱引用对象的容器.

- (NSMutableArray <NSValue *> *)observers {
    if (!_observers) {
        _observers = [NSMutableArray array];
    }

    return _observers;
}

- (void)addObserver:(id<CSDownloadOperationQueueDelegate>)observer {
    @synchronized (self.observers) {
        BOOL isExisting = NO;

        for (NSValue *value in self.observers) {
            if ([value.nonretainedObjectValue isEqual:observer]) {
                isExisting = YES;
                break;
            }
        }

        if (!isExisting) {
            [self.observers addObject:[NSValue valueWithNonretainedObject:observer]];
            NSLog(@"@");
        }
    }
}

- (void)removeObserver:(id<CSDownloadOperationQueueDelegate>)observer {
    @synchronized (self.observers) {
        NSValue *existingValue = nil;

        for (NSValue *value in self.observers) {
            if ([value.nonretainedObjectValue isEqual:observer]) {
                existingValue = value;
                break;
            }
        }

        if (existingValue) {
            [self.observers removeObject:existingValue];
        }
    }
}
复制代码

Demo地址

CSSerialDownloader

转载于:https://juejin.im/post/5b18966b6fb9a01e324b43e3

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在网络编程中,多线程编程是一种常用的技术,可以提高程序的并发性和性能。下面是一些关于多线程编程的常用方法和注意事项: 1. NSThread:NSThread是iOS中最底层的线程类,它可以通过类方法或实例方法来创建线程。使用NSThread可以设置线程的名称、优先级,以及控制线程的睡眠和退出等操作。 2. 线程调度:在多线程编程中,多个线程会并发运行,但线程的执行顺序是由CPU调度决定的,程序员无法控制。多个线程会同时竞争CPU资源,谁先抢到资源谁就先执行,所以多线程的执行顺序是随机的。 3. 多线程的创建:在iOS开发中,常用的多线程编程方式有三种:NSThread、GCD和NSOperationNSThread是最底层的线程类,可以直接操作线程的各种属性和方法。GCD(Grand Central Dispatch)提供了一种高效的并发编程模型,可以通过队列来管理任务的执行。NSOperation是基于GCD的更高层次的封装,提供了更多的控制和管理线程的功能。 4. 线程的创建顺序:在多线程编程中,并不能保证哪个线程会先运行,即无法确定新创建的线程或调用线程哪个会先执行。新创建的线程可以访问进程的地址空间,并继承调用线程的浮点环境和信号屏蔽字,但挂起信号集会被清除。 总结来说,多线程编程是一种提高程序并发性和性能的技术,在网络编程中尤为重要。通过使用NSThread、GCD或NSOperation等方法,可以实现多线程的创建和管理。然而,程序员无法控制线程的执行顺序,因为线程的调度是由CPU调度决定的。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [IOS之多线程基础(OC)](https://blog.csdn.net/yong_19930826/article/details/105857055)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [UNIX环境高级编程笔记](https://blog.csdn.net/w_x_myself/article/details/128613534)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值