关于网络请求的方法

1、顺序请求数据

在开发中,数据请求可能需要进行逐步逐个进行。需要用到NSOperationQueue。具体如下:

NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{
    //默认创建的信号为0
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    //这里是请求的方法(自定义或者AFN)
    [[ZSKNNetworking shareInstance] requestDataWithBusCode:@"" TransactionID:@"" 
TimeStamp:@"" ReqInfo:productLabelReqInfo type:(HttpRequestTypeGet) 
success:^(id responseObject) {       
            //这里请求成功信号量 +1 为1
            dispatch_semaphore_signal(semaphore);
        } failure:^(NSError *error) {
            //这里请求成功信号量 +1 为1
            dispatch_semaphore_signal(semaphore);
        }];
}];

NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{
    //默认创建的信号为0
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    //这里是请求的方法(自定义或者AFN)
    [[ZSKNNetworking shareInstance] requestDataWithBusCode:@"" TransactionID:@"" 
TimeStamp:@"" ReqInfo:productLabelReqInfo type:(HttpRequestTypeGet) 
success:^(id responseObject) {
            //这里请求成功信号量 +1 为1
            dispatch_semaphore_signal(semaphore);
        } failure:^(NSError *error) {
            //这里请求成功信号量 +1 为1
            dispatch_semaphore_signal(semaphore);
        }];
}];

NSBlockOperation *operation3 = [NSBlockOperation blockOperationWithBlock:^{
    //默认创建的信号为0
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    //这里是请求的方法(自定义或者AFN)
    [[ZSKNNetworking shareInstance] requestDataWithBusCode:@"" TransactionID:@"" 
TimeStamp:@"" ReqInfo:productLabelReqInfo type:(HttpRequestTypeGet) 
success:^(id responseObject) {
            //这里请求成功信号量 +1 为1
            dispatch_semaphore_signal(semaphore);
        } failure:^(NSError *error) {
            //这里请求成功信号量 +1 为1
            dispatch_semaphore_signal(semaphore);
        }];
}];    
//这是顺序执行方法
[operation2 addDependency:operation1];
[operation3 addDependency:operation2];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
//放入到队列中
[queue addOperations:@[operation1, operation2, operation3] waitUntilFinished:NO];
//添加关于信号量的监听通知
[queue addObserver:self forKeyPath:@"operationCount" options:0 context:nil];
以上是在方法中的内容。

//添加监听(数据请求)
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    
    if ([keyPath isEqualToString:@"operationCount"]) {
        NSOperationQueue *queue = (NSOperationQueue *)object;
        if (queue.operationCount == 0) {
            NSLog(@"全部完成");
        }
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容