0

我正在通过 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];
    });
}
4

1 回答 1

3

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

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

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

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

编辑: NSURLSession 提供了一个带有可能有用的完成处理程序的 API。您可以使用它代替委托: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
于 2016-01-09T00:22:34.550 回答