我如何等待完成块完成objective-c ios

时间:2016-07-03 07:22:06

标签: ios objective-c semaphore completionhandler completion-block

我有两个方法的子类:

- (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之前,UI会使用活动指示器进行处理,以便我们可以等待。我如何等待两个完成块返回?

2 个答案:

答案 0 :(得分:2)

- (void *) verifyUniqueCompletion:(void (^)(NSString *result, NSError *error))completion
{
    // 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) {
             completion(nil, error);
         } else {  

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

             completion(verifyUnique, nil);
             // return verifyUnique;
             // dispatch_semaphore_signal(semaphore);
         }
     }];

    // dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

}

使用此:

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

答案 1 :(得分:1)

您可以在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) {

}];