Bashir Sidani Bashir Sidani - 5 months ago 7
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

validateConnection
that returns a
bool
. This function makes a call to the server (using anetworking) and returns
true
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
bool
: how to achieve that?

Any help would be much appreciated!

Answer

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) {
        if(success)
        {
            NSLog(@"==%@",responce); // here you get response once method camplet
        }
    }];