我正在使用Objective-c傳遞一條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;
uj5u.com熱心網友回復:
您已將委托佇列指定為主佇列。但是你已經用dispatch_semaphore_wait. 這是一個經典的死鎖,等待代碼在被阻塞的佇列上運行。
您可以指定nil會話的委托佇列,然后就不會死鎖。或使用[NSURLSession sharedSession].
我還鼓勵您考慮完全消除信號量。我理解信號量的吸引力,但它幾乎總是錯誤的解決方案。Apple 洗掉同步網路 API 是有原因的。信號量技巧感覺像是一種直觀的解決方法,但它效率低下,導致不合標準的用戶體驗,甚至可能導致您的應用程式在某些情況下被看門狗行程終止。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/496054.html
標籤:目标-c
上一篇:java-類屬性型別隨繼承而變化
