iOS: Waiting for API Completion Block and returning the result

房东的猫 提交于 2019-12-24 12:26:08

问题


Using inheritance.

I have a child class that calls a method in the parent class that runs calls the server API.

-(IBAction)buttonPressed
{
    [self methodInParentClassThatCallsTheAPI:param];
    // This is where I would like the call back
     if (success from the server API) // do something with the UI
     else if (failure from the server API) // do so something else with the UI
}

Parent Class:

- (void)methodInParentClassThatCallsTheAPI:(NSString *)param
{
      //The method below calls the server API and waits for a response.  
      [someServerOperation setCompletionBlockWithSuccess:^(param, param){
        // Return a success flag to the Child class that called this method
      } failure:^(param, NSError *error){
        // Return a failure flag to the Child class that called this method
      }
}

How can I accomplish this with a block? Is there a better way to do this other than the block? Code example please


回答1:


Create a completion block on methodInParentClass like this:

- (void)methodInParentClassThatCallsTheAPI:(NSString *)param completionBlock:(void (^)(BOOL success))completionBlock;

Then fire it inside the block success/failure with the appropriate value like this:

completionBlock(YES);

EDIT: By the way, please note that the return may not be on the main thread so if you plan to do a UI update you can fire the return block with a dispatch_async(dispatch_get_main_queue, ^{});

EDIT2: Since you seem to suggest this is the result of a button tap if your child is a VC waiting on the return just remember that this block will return async (obviously since that's what it is designed for) so if you need to hold the user for whatever reason you'll need to have the main thread display a loading indicator of some sort and hold user input events. Just remember that if you don't the UI will continue responding when before the completion block fires so at the very least you will want to disable the button so the user can't multi-press it and then you can reenable it when the completion block fires from the child VC.

EDIT3: Ok here is the calling code.

-(IBAction)buttonPressed
{
    [self methodInParentClassThatCallsTheAPI:param withCompletionBlock:^(BOOL success){
        if (success) {
          // do something with the UI
        } else {
            // Do something else
        }
    }];
}


来源:https://stackoverflow.com/questions/23507331/ios-waiting-for-api-completion-block-and-returning-the-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!