gpt4 book ai didi

ios - 在继续之前等待 AFHTTPRequestOperation 完成

转载 作者:行者123 更新时间:2023-11-28 22:39:40 24 4
gpt4 key购买 nike

我正在尝试制作一个使用 AFHTTPClient 与 API 通信的 iOS 应用程序。第一步是对用户进行身份验证,为此,我使用以下代码:

-(void)authorize
{
NSURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"login.php" parameters:@{@"login": account.username, @"passwd":account.password}];

AFHTTPRequestOperation *operation = [httpClient HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
[httpClient setDefaultHeader:@"Token" value:[[operation.response allHeaderFields] objectForKey:@"CSRF-Token"]];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@",error.localizedDescription);
}];
[httpClient enqueueHTTPRequestOperation:operation];
[httpClient.operationQueue waitUntilAllOperationsAreFinished];
}

如您所见,我的代码从服务器响应中获取 token 并将其设置为所有 future 请求的默认 header 。

然后我使用 - (void)postPath:(NSString *)path parameters:(NSDictionary *)parameters success:success failure:failure 继续其他请求

但是当我使用调试器时,我发现那些在授权操作完成之前执行的其他请求,因此它们失败了,因为它们没有授权 token 。我添加了 [httpClient.operationQueue waitUntilAllOperationsAreFinished]; 但它似乎不起作用...

谢谢你的帮助

最佳答案

使用 dispatch semaphore .

-(void)authorize
{
dispatch_semaphore_t done = dispatch_semaphore_create(0);
NSURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"login.php" parameters:@{@"login": account.username, @"passwd":account.password}];

AFHTTPRequestOperation *operation = [httpClient HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
[httpClient setDefaultHeader:@"Token" value:[[operation.response allHeaderFields] objectForKey:@"CSRF-Token"]];
dispatch_semaphore_signal(done);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@",error.localizedDescription);
}];
[httpClient enqueueHTTPRequestOperation:operation];
[httpClient.operationQueue waitUntilAllOperationsAreFinished];
dispatch_semaphore_wait(done, DISPATCH_TIME_FOREVER);
}

请注意,这会阻止该方法返回,因此您需要确保它不在主/UI 线程上。

关于ios - 在继续之前等待 AFHTTPRequestOperation 完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14925702/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com