How to react to asynchronous events (login)?

最后都变了- 提交于 2019-12-01 01:43:32

The simplest solution would be to pass a completion block that can be executed once the login completes. In addition, you could pass a block that gets called if there is an error. In my applications I have wrapped this into a 'responder' pattern where you define a class that contains a completion and error block. That is passed as an argument to asynchronous methods. The only catch here is that you have to write the login to 'execute' the blocks at the appropriate time.

I have implemented this pattern several times on applications that use asynchronous API's (including the Facebook SDK).

UPDATE (added some code samples):

In its simplest form, you could just add a completion block. First, you would want to create a typedef for your completion block. In this case, we'll use a block that returns no value and has an id input:

typedef void (^successBlock)(id);

Next, you could create a controller that creates a facade for your interaction with the Facebook class. In this facade, you could create a login method that has a signature like this (this assumes you have an iVar of type successBlock):

- (void)loginWithCompletionHandler:(successBlock)handler
{
    // If you aren't using ARC - you'll need to use Block_copy(handler)
    completionHandler = handler;

    [facebook authorize:facebookSettings.defaultPermissions 
               delegate:self];
}

Finally, in your FBSessionDelegate implementation, you can execute this block:

#pragma mark - FBSessionDelegate Implementation

- (void)fbDidLogin
{
    // Store Facebook token, etc.....

    if( completionHandler )
    {
        // You could pass any data you want in this data property
        completionHandler(data);
    }
}

}

The 'Responder' pattern I mentioned above is a bit more involved than this, but this should be enough to get you going.

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