美文网首页
iOS 等待异步操作后 return 值

iOS 等待异步操作后 return 值

作者: 30213be71330 | 来源:发表于2019-10-15 09:01 被阅读0次

    需求是:一个函数 等AFNetwork 网络 请求完成后,修改返回值,并继续执行函数,并返回值.

    - (BOOL)Action_alertAgreement
    {
        
        dispatch_semaphore_t signal = dispatch_semaphore_create(0);
    
        __block BOOL returnValue = NO;
        HWHttpRequestOperationManager *httpManager = [HWHttpRequestOperationManager baseManager];
        httpManager.completionQueue = dispatch_get_global_queue(0, 0);
        [httpManager postHttpRequest:kGetOrgAgreementInfo parameters:nil queue:nil success:^(NSDictionary * _Nullable responseObject) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [Utility_new showToastWithMessage:remark];
                });
                returnValue = NO;
            }
            dispatch_semaphore_signal(signal);
    
        } failure:^(NSString * _Nullable code, NSString * _Nullable error) {
            returnValue = NO;
            dispatch_semaphore_signal(signal);
        }];
        dispatch_semaphore_wait(signal, DISPATCH_TIME_FOREVER);
        return returnValue;
    }
    
    

    关键的一步是设置httpManager.completionQueue = dispatch_get_global_queue(0, 0);要不然会阻塞主线程.并且如果要在AFNetwork的回调中操作UI,要切换到主线程. HWHttpRequestOperationManager 是对AFNetwork的进一步封装,可以忽略.

    相关文章

      网友评论

          本文标题:iOS 等待异步操作后 return 值

          本文链接:https://www.haomeiwen.com/subject/yzawyctx.html