Reputation: 1024
I have a method that should return a dict:
-(NSDictionary *) searcherMethod: (NSString *) text {
[ReadService readFromApi:APIURL
whenFinish:^(id responseObject) {
//HERE I have A response from API
NSDictionary *response = (NSDictionary*)responseObject;
//HOW searcherMethod can return the response dict?
return response;
}];
}
How make that searcherMethod can return the response dict?
Upvotes: 2
Views: 241
Reputation: 162
The response from the API call return asynchronously, so you have to write block for return the result while you have got the response from API.
The below code help you to achieve your requirements.
This code will return response asynchronously
-(void) searcherMethod: (NSString *) text responseCompletion:(void (^_Nullable)(NSDictionary *))responseCompletion{
[ReadService readFromApi:APIURL
whenFinish:^(id responseObject) {
//HERE I have A response from API
NSDictionary *response = (NSDictionary*)responseObject;
//HOW searcherMethod can return the response dict?
if (responseCompletion) {
responseCompletion(response);
}
}];
}
This code will return response synchronously
-(NSDictionary *) searcherMethod: (NSString *) text {
NSDictionary *response = nil;
// create the semaphore for synchronously call
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[ReadService readFromApi:APIURL
whenFinish:^(id responseObject) {
//HERE I have A response from API
response = (NSDictionary*)responseObject;
// fire signal for semaphore so your code will execute further
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
return response;
}
Semaphore is blocking the execution until the signal is not received, this will return your method after receiving the response.
you can use below code for the method call.
[self searcherMethod:@"responseText" responseCompletion:^(NSDictionary *responseDict) {
//result
NSLog(@"Response : %@",responseDict);
}];
Now you can call your method synchronously
NSDictinary *response = [self searcherMethod:text]
Hope this will help you.
Upvotes: 2