iOS:等待API完成阻止并返回结果 [英] iOS: Waiting for API Completion Block and returning the result

查看:110
本文介绍了iOS:等待API完成阻止并返回结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用继承。

我有一个子类,它调用运行的父类中的方法调用服务器API。

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
}

父类:

- (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

推荐答案

methodInParentClass 上创建一个完成块,如下所示:

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);

编辑:顺便提一下,请注意返回可能不在主线程上,所以如果你计划进行UI更新,您可以使用dispatch_async(dispatch_get_main_queue,^ {})触发返回块;

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:因为您似乎建议这是结果一个按钮点击如果你的孩子是等待返回的VC只记得这个块将返回异步(显然因为它是它的设计目的)所以如果你因为某种原因需要持有用户你需要拥有主线程显示某种加载指示符并保存用户输入事件。请记住,如果你没有UI将在完成块激活之前继续响应,所以至少你会想要禁用按钮,这样用户就不能多按它然后你可以在完成时重新启用它阻止来自孩子VC的火灾。

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
        }
    }];
}

这篇关于iOS:等待API完成阻止并返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆