在iOS中的异步nsurlsession内调用sync nsurlsession

时间:2018-09-21 15:02:30

标签: ios objective-c nsurlsession

我正在尝试在异步nsurlsession调用中调用同步nsurlsession调用,但是它不起作用。同步通话未完成。下面是代码。

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"URL1"]];
    [request setHTTPMethod:@"GET"];

    // Call first service
    [[NSURLSession.sharedSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        if(data){
            // If first webservice is successful then dont call second service
            return;
        }

        // Call second service
        NSMutableURLRequest *request2 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"URL2"]];
        [request2 setHTTPMethod:@"GET"];

        dispatch_semaphore_t sem = dispatch_semaphore_create(0);

        [[NSURLSession.sharedSession dataTaskWithRequest:request2 completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

            dispatch_semaphore_signal(sem);

        }] resume];

        dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);

    }] resume];

1 个答案:

答案 0 :(得分:0)

正如@Larme所说,最好将一个完成块传递到您的方法中,然后在两个请求的完成块中调用它(看起来您想使用第一个Web服务中的数据,因为它有一些,然后第二个(如果没有的话):

- (void)webServiceRequestWithCompletion:(void (^_Nullable)(NSData *_Nullable completionData, NSError *_Nullable error))completionAfter {
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"URL1"]];
    [request setHTTPMethod:@"GET"];
    // Call first service
    [[NSURLSession.sharedSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            // If first webservice is successful then dont call second service
            if (completionAfter) {
                completionAfter(data, error);
            }
            return;
        }
        // Call second service
        NSMutableURLRequest *request2 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"URL2"]];
        [request2 setHTTPMethod:@"GET"];
        [[NSURLSession.sharedSession dataTaskWithRequest:request2 completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (completionAfter) {
                completionAfter(data, error);
            }
        }] resume];
    }] resume];
}

然后您将用类似这样的名称来调用它:

[self webServiceRequestWithCompletion:^(NSData *completionData, NSError *error) {
    // do stuff with data returned from one of the two webservices here
}];

如果这不是您要尝试的操作,那么您需要编辑您的问题并提供其他上下文,以围绕该代码的调用方式以及为什么必须使用信号量(等待什么)? )

此站点有助于您理解如何使用块语法:http://goshdarnblocksyntax.com

苹果在这里有一些不错的文档:https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithBlocks/WorkingwithBlocks.html