如何在objective-c ios中等待完成块完成

如何在objective-c ios中等待完成块完成,ios,objective-c,semaphore,completionhandler,completion-block,Ios,Objective C,Semaphore,Completionhandler,Completion Block,我有一个具有两种方法的子类: - (void) aPostRequest:(NSString *) urlStr andJSON:(NSMutableDictionary*) jsonDict completion:(void (^)(NSDictionary *, NSError *))completion { NSError *error = nil; NSURLSessionConfiguration *configuration = [NSURLSessionConfi

我有一个具有两种方法的子类:

- (void) aPostRequest:(NSString *) urlStr andJSON:(NSMutableDictionary*) jsonDict completion:(void (^)(NSDictionary *, NSError *))completion
{
    NSError *error = nil;

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

    [request setHTTPMethod:@"POST"];

    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

    // Set up the post data
    NSData *postData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:nil];
    [request setHTTPBody:postData];

    // dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
    {
        if (!error)
        {
            // convert the NSData response to a dictionary
            NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];

            if (error)
            {
                // There is a parse error
                completion(nil, error);
            }
            else
            {
                // Success
                completion(dictionary, nil);
            }
        }
        else
        {
            // Error from the session
            completion(nil, error);
        }
        // dispatch_semaphore_signal(semaphore);
    }];
    // dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    [postDataTask resume];
}
此方法调用上述方法:

- (NSString *) verifyUnique
{
    // JSON data
    __block NSString *verifyUnique = nil;

    // dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

    // URL string
    NSString *url = @"https://the-website-to-handle-this.com";
    NSMutableDictionary *json = [[NSMutableDictionary alloc] init];
    [json setValue:@"testing" forKey:@"name"];

    [self aPostRequest:url andJSON:json completion:^(NSDictionary *response, NSError *error)
     {
         // dispatch_semaphore_signal(semaphore);

         if (!error) {

         } else {  

             verifyUnique = [response objectForKey:@"uniqueness"]; 

             // return verifyUnique;
             // dispatch_semaphore_signal(semaphore);
         }
     }];

    // dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

    return verifyUnique;
}

我从另一个视图控制器类调用该函数,并调用
[thisClass verifyUnique]
并希望它等待答案返回。在视图控制器中调用它之前,UI使用活动指示器进行处理,以便我们可以等待。如何等待两个完成块返回?

您可以在
verifyUnique
中添加完成块作为参数:

- (void)verifyUnique:(void (^)(NSString * str))handler{

     // JSON data
     __block NSString *verifyUnique = nil;

     // dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

    // URL string
    NSString *url = @"https://the-website-to-handle-this.com";
    NSMutableDictionary *json = [[NSMutableDictionary alloc] init];
   [json setValue:@"testing" forKey:@"name"];

   [self aPostRequest:url andJSON:json completion:^(NSDictionary *response, NSError *error)
 {
     // dispatch_semaphore_signal(semaphore);

     if (!error) {
          handler(@"");
     } else {  

         verifyUnique = [response objectForKey:@"uniqueness"]; 

         handler(verifyUnique);
     }
 }];


}
您可以这样使用它:

[object verifyUnique:^(NSString *verifyUnique) {

}];
使用以下命令:

[thisClass verifyUniqueCompletion:^(NSString *result, NSError) {
    NSLog(@"result: ", result);
}];

这是一个快速的答案,我使用的是objective cYep,但是这里的想法,以及下面的两个答案,是您正在调用异步方法,所以您应该自己采用异步模式,并使用自己的完成处理程序模式,而不是等待响应。什么是异步模式?(我不知道swift,所以我很难读懂)另请看@cdub——异步模式只是一种用于解决特定问题的设计,在本例中是异步编程。最常见的异步模式之一是完成处理程序模式,即方法异步运行,但提供了完成处理程序参数,调用方可以通过该参数指定异步任务完成时应执行的代码。事实上,
dataTaskWithRequest
aPostRequest
都采用了这种模式,我们都建议您自己的
verifyUnique
也采用这种模式。请检查我编辑的答案。因此,如果我想在if语句中使用上面的结果,它必须位于该块的内部,对吗?比如如果(结果==@是
[thisClass verifyUniqueCompletion:^(NSString *result, NSError) {
    NSLog(@"result: ", result);
}];