Reputation: 1663
I am trying to wait until my rest service call back receive, but after
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
line, everythings stop and i never receive call back. My code is below.
__block NSString *strTaggedText=@"";
dispatch_semaphore_t sem;
sem = dispatch_semaphore_create(0);
[[manager2 dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
NSLog(@"Reply JSON: %@", responseObject);
dictionary=[responseObject objectForKey:@"****"];
strTaggedText=[dictionary objectForKey:@"Text"];
NSLog(@"strText = %@",strTaggedText);
} else
{
NSLog(@"Error: %@, %@, %@", error, response, responseObject);
}
dispatch_semaphore_signal(sem);
}] resume];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
return strTaggedText;
Upvotes: 1
Views: 527
Reputation: 52538
The reason that this isn't working at all is that you wrote
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
on the main thread, and the main thread stops right there until a _signal comes - which won't arrive because your manager2 will never reach the code where it resumes the data task.
Upvotes: 1
Reputation: 9721
You've stopped the main runloop, which means no events are getting processed and the app will stop responding.
You are calling an asynchronous method and the main thread is expected to return immediately, after perhaps showing a busy indicator.
Processing is meant to continue from within the block, which will be called in a background thread. You can then push the data to whereever it's expected to go and cancel the busy indicator. The next thing can then be triggered, perhaps on the main thread, but that's up to you; certainly any UI-interaction must be done on the main thread only.
This is asynchronous programming, but a full discussion is beyond the scope of a stackoverflow answer, in my opinion.
Upvotes: 1