我在Objective中使用POST传递一条NSURLSessionDataTask消息。
传输任务是非阻塞的.我必须等待结果,所以我使用dispatch_semaphore_t来等待。
不幸的是,当调用相应的函数时,任务不能工作,为什么?下面的代码如下所示。
NSString *urlString = [NSString stringWithFormat:@"http://localhost/api/test"];
char json_string[20] = "reqtestmsg";
size_t jsonLength = strlen(json_string);
NSData *jsonBodyData = [NSData dataWithBytes:json_string length:jsonLength];
NSMutableURLRequest *request = [NSMutableURLRequest new];
request.HTTPMethod = @"POST";
// for alternative 1:
[request setURL:[NSURL URLWithString:urlString]];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody:jsonBodyData];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config
delegate:nil
delegateQueue:[NSOperationQueue mainQueue]];
printf ("curl semaphore\n");
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
__block bool result = false;
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:^(NSData * _Nullable data,
NSURLResponse * _Nullable response,
NSError * _Nullable error) {
NSHTTPURLResponse *asHTTPResponse = (NSHTTPURLResponse *) response;
NSLog(@"curl The response is: %@", asHTTPResponse);
if (asHTTPResponse.statusCode == 200) {
printf ("curl status 200 ok\n");
result = true;
}
dispatch_semaphore_signal(semaphore);
}];
[task resume];
printf ("curl wait!!!");
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); // ==> blocked , task does not work!!!!
printf ("curl wait!!! -1");
return result;发布于 2022-06-27 00:22:23
您已指定委托队列为主队列。但是您已经用dispatch_semaphore_wait阻塞了主线程。这是一个典型的死锁,等待代码在阻塞的队列上运行。
您可以为会话的委托队列指定nil,这样就不会出现死锁。或者使用[NSURLSession sharedSession]。
我也鼓励你考虑完全取消信号量。我理解信号量的吸引力,但它几乎总是错误的解决方案。苹果公司删除同步网络API是有原因的。信号量的技巧感觉就像一个直观的解决方案,但它效率低下,导致不合格的UX,甚至可能导致你的应用程序在某些情况下被看门狗程序终止。
https://stackoverflow.com/questions/72765834
复制相似问题