gpt4 book ai didi

ios - 在填充静态 TableView 之前等待 HTTP Web 请求完成

转载 作者:行者123 更新时间:2023-12-01 19:11:30 24 4
gpt4 key购买 nike

我有一个静态 UITableView,我想用使用 HTTP 请求(异步运行)检索到的数据来填充它。我试图在几个地方发出 HTTP 请求,但是每次请求中的数据都来得太晚并且没有填充表格 View 。我发现填充表格 View 的唯一方法是调用 reloadData如下:

- (void)viewDidLoad
{
[super viewDidLoad];

// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;

// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;

_accountModel = [[CatapultAccount alloc] init];

[_accountModel getCurrentClient:^ (BOOL completed, NSDictionary *currentAccount) {
if (completed) {
_account = currentAccount;
[self.tableView reloadData];
} else {
UIAlertView *errorMessage = [[UIAlertView alloc] initWithTitle:@"Account retrieval unsuccessful"
message:@"Unable to retrieve current account information"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];

[errorMessage show];
}
}];
}

我试图让请求在主线程上运行,但它似乎已经在主线程上运行……我怀疑这是从 getCurrentClient 内部调用的实际请求在后台运行:
- (void)getCurrentClient:(void (^)(BOOL completed, NSDictionary *account))completion
{
__block BOOL operationSuccessful = NO;
__block NSDictionary *currentClient = nil;
NXOAuth2Account *currentAccount = [[[NXOAuth2AccountStore sharedStore] accounts] lastObject];

[NXOAuth2Request performMethod:@"GET"
onResource:[NSURL URLWithString:[NSString stringWithFormat:@"%@/clients/%@", kCatapultHost, currentAccount.userData[@"account_name"]]]
usingParameters:nil
withAccount:currentAccount
sendProgressHandler:nil
responseHandler:^ (NSURLResponse *response, NSData *responseData, NSError *error) {
if (error != nil) {
operationSuccessful = NO;
#if DEBUG
NSLog(@"ERROR: %@", error);
#endif
}
else {
operationSuccessful = YES;

NSError *jsonError;

currentClient = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&jsonError];

if (jsonError != nil) {
operationSuccessful = NO;
#if DEBUG
NSLog(@"Error: %@", jsonError);
#endif
}
}

completion(operationSuccessful, currentClient);
}];
}

那么我的方法(调用 reloadData)是好方法吗?没有办法让表格 View Controller 等待请求完成吗?

最佳答案

不,您不能让 TableView Controller 等待。调用重新加载数据是来自 Web 服务的回调的正常模式。如果您在显示一些数据之前等待网络调用完成,那么您无能为力。这里有一些想法......

您可能会在加载时显示进度指示器。

或者,如果您在此之前有另一个 View Controller ,您可以按下一个触发加载数据的按钮,当请求完成时,它将新的 TableView Controller 推送到屏幕上,数据准备就绪。

更高级的是在模型对象上使用键值观察 (KVO)。您的表将使用模型对象作为其数据源。您从网络加载并使用结果填充模型对象。 KVO 将处理通知静态表新数据已经到达并且它应该显示它(而不是重新加载整个表)......但是你仍然会在开始时处于空白状态。

关于ios - 在填充静态 TableView 之前等待 HTTP Web 请求完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16307456/

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