gpt4 book ai didi

ios - NSDictionary 没有及时填充

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

我正在执行用户名/密码检查,方法是对服务器执行 ping 操作以获取 JSON 文件,然后检查该文件对。当我检查它时,我的 userDictionary 没有填充。我假设这是因为 NSURLSession 是异步的,它只是在我需要它时没有取回数据。在我的 ServerCommunicationModel 中,我有:

- (void)getUserDictionaryFromServer
{
NSString *userFileURLString = [NSString stringWithFormat:@"%@/userFile.json", REMOTE_PATH_TO_ROOT_APP_FOLDER];
NSURL *userFileURL = [NSURL URLWithString:userFileURLString];

NSURLSessionDataTask *userFileTask = [self.session dataTaskWithURL:userFileURL
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSDictionary *returnJSON = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
self.userDictionary = [returnJSON objectForKey:@"users"];
}];

[userFileTask resume];
}

然后在 View Controller 中:

- (IBAction)submitButtonPressed:(UIButton *)sender
{
_usernameEntered = self.usernameTextField.text;
_passwordEntered = self.passwordTextField.text;

// Make sure the user put something in for a username and password
if ([_usernameEntered isEqualToString:@""] || [_passwordEntered isEqualToString:@""])
{
[self showAlertViewWithText:@"" :@"Please enter a username and password" :@"OK"];
}

// Stow a spinner while checking credentials
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void)
{
// Get the user file from the server
WAServerCommunicationModel *server = [WAServerCommunicationModel sharedInstance];
[server getUserDictionaryFromServer];
self.users = [server userDictionary];

if ([self goodUser])
{
[self performSegueWithIdentifier:@"loginOK" sender:self];

} else
{
[self showAlertViewWithText:@"" :@"Invalid Username or Password" :@"Try Again"];
}

[MBProgressHUD hideHUDForView:self.view animated:YES];
});
}

最佳答案

您可以修改 getUserDictionaryFromServer 方法并添加成功/失败参数,如下所示:

- (void)getUserDictionaryFromServerWithSuccess:(void (^)(NSDictionary * userDictionary))success
failure:(void (^)(NSError *error))failure;

然后,在从服务器获取响应时调用适当的回调(成功/失败)。

这样做之后,如果您在成功 block 中调用 [server userDictionary];,它将始终被正确填充。

编辑:NSURLSession 提供了一个带有 completionHandler 的 API,这可能很有用。您可以使用它代替委托(delegate):https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSession_class/index.html#//apple_ref/occ/instm/NSURLSession/dataTaskWithRequest:completionHandler :

- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
completionHandler:(void (^)(NSData *data,
NSURLResponse *response,
NSError *error))completionHandler

关于ios - NSDictionary 没有及时填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34688184/

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