我正在執行一個用戶名/密碼檢查,通過ping服務器的JSON文件,然後檢查它的配對。當我檢查它時,我的userDictionary
未填充。我假設這是因爲NSURLSession
是異步的,它只是在我需要的時候沒有得到數據。在我ServerCommunicationModel
,我有:NSDictionary沒有及時填充
- (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];
});
}
我編輯它以包含完成處理程序(並更改了問題)。我仍然有一個問題,它沒有被填充第一次按下提交按鈕。如果我再次按下提交按鈕,它將被填充。 –
@WillLuce我沒有看到你添加成功/失敗塊getUserDictionaryFromServer方法就像我提到的。在完成處理程序塊中添加完成後,如果錯誤爲零,則可以調用成功塊。 – pshah