Bashir Sidani Bashir Sidani - 1 year ago 45
iOS Question

How to make method wait for a response in order to return a value?

I am sure this has been asked before, but I don't know the keywords to search for it.

Suppose that I have a function

that returns a
. This function makes a call to the server (using anetworking) and returns
if the request was successful (this is just a example).

I want my method to wait until the response is back in order to return the
: how to achieve that?

Any help would be much appreciated!

Answer Source

Its Called Block you can learn more about block by Introduction to Objective-C Blocks

Following is the sample method to create block and its call back:

-(void)callmethodwith:(NSString*)string withCompletion:(void(^)(BOOL success, NSError* error, id responce))completion

    NSString *str =[NSString stringWithFormat:@"MY FUNTn CALLBACK %@",string];
    if (completion){
        dispatch_async(dispatch_get_main_queue(), ^{
            completion(YES,nil,str); // here that call when method complete

And you can call it like following:

[self callmethodwith:@"My new" withCompletion:^(BOOL success, NSError *error, id responce) {
            NSLog(@"==%@",responce); // here you get response once method camplet