gpt4 book ai didi

ios - AFNetworking 在第一次运行时返回 null

转载 作者:行者123 更新时间:2023-11-29 00:37:27 25 4
gpt4 key购买 nike

我有一个列表,当用户点击列表中的一项时,他会根据 HTTP 请求的响应重定向到另一个页面。

代码:

-(void) checkCardPresent{

// NSOperationQueue *networkQueue = [[NSOperationQueue alloc] init];
// networkQueue.maxConcurrentOperationCount = 5;
NSURL *url = [NSURL URLWithString:@"https://XXXXXXX/getCardDetails"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
if([string isEqualToString:@""]){
self.isCardPresent = NO;
}
else{

self.isCardPresent = YES;
}
NSLog(@"%@", string);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%s: AFHTTPRequestOperation error: %@", __FUNCTION__, error);
}];
//[networkQueue addOperation:operation];

问题:现在,当我首先单击该项目时,我会进入错误的页面。但是,再次返回该页面并再次单击时,我将进入正确的页面。

更多数据:此代码检查用户是否添加了付款方式。收到返回的空白文本后,他将被带到页面 A。

收到卡数据的正确响应后,他将被带到页面 B。

调查:

上面的代码示例在第一次单击时不会引起任何操作,只是终止(无 HTTP 请求)。但是,第二次单击时,它会返回卡详细信息。即执行 HTTP 请求。

有谁知道这是怎么回事吗?

最佳答案

我认为正在发生的事情是您的导航条件正在同步运行,但正在检查的条件取决于异步设置的状态。这是推测,但这是一个常见错误,与您看到的错误的首次行为一致。

您的导航代码目前可能看起来像这样......

// on selection of an item
[self checkCardPresent];
if (self.isCardPresent) {
// push to some vc
} else {
// push to some other vc
}

但是,一旦网络工作完成,isCardPresent 就会在条件运行后设置好。

要解决这个问题,请在您的网络调用中添加一个完成 block ,然后使用该 block 进行导航。像这样的……

// invoke completion with YES on success, no otherwise
- (void)checkCardPresentWithCompletion:(void (^)(BOOL))completion {
NSURL *url = [NSURL URLWithString:@"https://XXXXXXX/getCardDetails"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
if([string isEqualToString:@""]){
self.isCardPresent = NO;
} else {
self.isCardPresent = YES;
}
NSLog(@"%@", string);
if (completion) completion(YES);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%s: AFHTTPRequestOperation error: %@", __FUNCTION__, error);
if (completion) completion(NO);
}];
}

现在,在网络请求完成后进行导航...

// on selection of an item
// show some UI to indicate that we're busy
[self checkCardPresentWithCompletion:^(BOOL success) {
// remove the UI that indicates we're busy
if (success) {
if (self.isCardPresent) {
// push to some vc
} else {
// push to some other vc
}
} else {
// show UI to indicate an error
}
}];

关于ios - AFNetworking 在第一次运行时返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40291721/

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