gpt4 book ai didi

ios - 在 block 内返回 BOOL 方法?

转载 作者:行者123 更新时间:2023-11-29 10:30:42 24 4
gpt4 key购买 nike

我有一个 bool 方法,它为输入的字符串返回是或否。我成功地能够返回 YESNO,但我似乎无法建立网络连接并返回 YESNO 取决于服务器的响应。我尝试使用 __block 并且我不觉得它会等待网络请求完成,有没有办法返回 YESNO 在成功 block 中没有给我错误:

Incompatible block pointer types sending 'BOOL(^)(NSURLSessionTask*__strong, NSError __strong' to parameter of the type 'void(^)(NSURLSessionTask...)

-(BOOL)customResponseForString:(NSString *)text {

__block BOOL response_available;

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObject:@"text/plain"]];
[manager GET:[NSString stringWithFormat:@"http://example.com/response.php?input=%@", text] parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {

NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSUTF8StringEncoding error:nil];
response_available = (BOOL)response[@"response_available"];
if (response_available) {
[session sendTextSnippet:response[@"response"] temporary:NO scrollToTop:NO dialogPhase:@"Summary"];
} else {
response_available = NO;
}

[session sendTextSnippet:[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] temporary:NO scrollToTop:NO dialogPhase:@"Summary"];

[session sendRequestCompleted];

} failure:^(NSURLSessionDataTask *task, NSError *error) {
//return NO;
}];
});

return response_available;

}

最佳答案

您的 block 定义语法可能是错误的,因为您肯定可以在 block 中返回一个 BOOL 以及其他参数。

- (void)fetchCurrentUserWithCompletion:(void (^)(BOOL success, User *user))completion;

这个方法会这样调用:

[self.userProfileController fetchCurrentUserWithCompletion:^(BOOL success, User *user) {
if (success) {
NSLog(@"Current User Name: %@", user.fullName);
}
}];

如果您使用 AFNetworking,请检查处理 completionBlocks 的 AFHTTPRequestOperation 对象:

[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
User *user = [self userFromResponseObject:responseObject];
if (completion) completion(YES, user);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (completion) completion(NO, user);
}];

关于ios - 在 block 内返回 BOOL 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29804874/

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