我正在通过 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];
}
然后在视图控制器中:
- (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];
});
}