简体   繁体   English

执行dispatch_semaphore_wait(sem,DISPATCH_TIME_FOREVER)之后,再也不会收到回调

[英]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);


    }
    dispatch_semaphore_signal(sem);

}] 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. 当然,任何UI交互都必须仅在主线程上完成。

This is asynchronous programming , but a full discussion is beyond the scope of a stackoverflow answer, in my opinion. 我认为这是异步编程 ,但是完整的讨论超出了stackoverflow答案的范围。

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. 在主线程上,并且主线程就在那里停止,直到_signal到达为止-该信号不会到达,因为您的manager2将永远不会到达恢复数据任务的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM