yucel bayram yucel bayram - 7 months ago 52
Objective-C Question

after execute dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER) never receive callback

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);


}] resume];

dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);

return strTaggedText;


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.