Completion handlers and return values

前端 未结 1 422
刺人心
刺人心 2020-12-28 22:52

I want to call a method which will return a value from its completion handler. The method performs asynchronously and I don\'t want to return a value before all the body of

相关标签:
1条回答
  • 2020-12-28 23:15

    You need to change getCurrentClient to take in a completion block instead of returning a value.

    For example:

    -(void)getCurrentClientWithCompletionHandler:(void (^)(NSDictionary* currentClient))handler
    {
        NXOAuth2Account *currentAccount = [[[NXOAuth2AccountStore sharedStore] accounts] lastObject];
    
        [NXOAuth2Request performMethod:@"GET"
                            onResource:[NSURL URLWithString:[NSString stringWithFormat:@"%@/clients/%@", kCatapultHost, currentAccount.userData[@"account_name"]]]
                       usingParameters:nil
                           withAccount:currentAccount
                   sendProgressHandler:nil
                       responseHandler:^ (NSURLResponse *response, NSData *responseData, NSError *error) {
                            NSError *jsonError;
    
                            NSDictionary* deserializedDict = [NSJSONSerialization JSONObjectWithData:responseData
                                                                                             options:kNilOptions
                                                                                               error:&jsonError];
                            handler(deserializedDict);
                    }];
    }
    

    It's important to remember that getCurrentClient will return immediately, while the network request is dispatched on another thread. Don't forget that if you want to update the UI using your response handler, you need to have your handler run on the main thread.

    0 讨论(0)
提交回复
热议问题