如何使一个函数等待另一个函数的回调?

时间:2019-06-22 03:05:02

标签: objective-c

我有两个功能: 函数A向服务器端发送请求,并具有回调以处理响应。在某个时候,例如某个网页开始加载并被触发。 函数B是常规函数,在某些时候,例如,当网页加载完成时,就会触发它。 功能A在功能B之前被触发。这意味着,当执行B时,A已经启动。 但是我希望函数B等待A中的回调完成,然后继续执行。 我想知道如何实施?

我已经阅读了有关信号量和NSCondition的信息,但示例均与父线程和子线程有关。就我而言,它们彼此独立。

1 个答案:

答案 0 :(得分:-1)

请尝试使用完成块。 遵循此代码结构...

-(void)serverRequestFetchData:(NSMutableURLRequest *)请求withCallback:(void(^)(NSArray *,NSError *))aCallback {

NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    dispatch_sync(dispatch_get_main_queue(), ^{
        NSHTTPURLResponse *statusResponse = (NSHTTPURLResponse *)response;
        if (statusResponse.statusCode >= 200 && statusResponse.statusCode < 300) {
            if (data.length > 0 && error == nil) {
                NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                if (aCallback) {
                    aCallback(array, nil);
                }
            } else {
                aCallback(@[], error);
            }
        } else {
            NSString *statusMessage = [NSString stringWithFormat:@"Invalid status response code: %ld", (unsigned long)statusResponse.statusCode];
            NSError *statusError = [[NSError alloc] initWithDomain:@"com.somedomain" code:10001 userInfo:@{NSLocalizedDescriptionKey : NSLocalizedString(statusMessage, nil)}];
            if (aCallback) {
                aCallback(@[], statusError);
            }
        }
    });
}];
[dataTask resume];

}

-(void)myRequest {

NSString *jsonRequest = [NSString stringWithFormat:@"{\"access_token\":\"ACCESS_TOKEN_HERE\"}"];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];

NSString *URLString = [NSString stringWithFormat:@"YOUR_FIRST_URL_STRING"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URLString]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", (int)[requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];

[self serverRequestFetchData:request withCallback:^(NSArray *array, NSError *error) {
    NSString *URLString = [NSString stringWithFormat:@"YOUR_SECOND_URL_STRING"];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URLString]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", (int)[requestData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody: requestData];

    [self serverRequestFetchData:request withCallback:^(NSArray *array, NSError *error) {

    }];
}];

}