NSDictionary 没有及时填充

NSDictionary not populating in time

我正在执行 username/password 检查,方法是向服务器发送 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];
    });
}

您可以修改 getUserDictionaryFromServer 方法并添加 success/failure 参数,如下所示:

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

然后,在从服务器获取响应时调用适当的回调 (success/failure)。

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

编辑: NSURLSession 提供了一个 API 和一个可能有用的 completionHandler 。您可以使用它代替委托: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