我在viewdidLoad上从我的应用程序调用服务器API,我想在后台进行,直到那时我在屏幕上显示UIActivityIndicator,当我得到API响应时,它应该被隐藏。怎么做??
答案 0 :(得分:1)
我有一段时间没有做过很多iOS的东西,也许有一个便利类或其他东西为你做这件事。但无论如何,你可以做类似以下的事情。
创建一个类来处理远程资源的获取,并让你想要调用它的类实现一个像MyAPIFetcherDelegate这样的协议,使用一个你可以调用的方法(比如resourceDidFinishLoading
)完成了。然后你做一些像
- (void)getResource
{
MyFetcher* fetcher = [[MyFetcher alloc] init];
fetcher.delegate = self;
// start/show the UIActivityIndicator
[NSThread detachNewThreadSelector:@selector(fetchResource:) toTarget:fetcher withObject:nil];
}
- (void)resourceDidFinishLoading
{
// Stop/Hide the UIActivityIndicator
// do something with the data that comes back
}
请注意,您可能必须传递一些数据才能实际处理您返回的结果,并且我从粗略的内存中键入了这些数据,因此可能存在错误。但这是一般的想法。从那里,您应该能够从文档中找到它。
另外,不要忘记考虑API中的错误。如果你超时,你不希望微调器坐在那里拒绝放弃屏幕。
答案 1 :(得分:0)
创建一个NSThread作为调用选择器,如下所示:
[NSThread detachNewThreadSelector:@selector(threadStartAnimating:) toTarget:self withObject:nil];
// Your code
[spinner stopAnimating];
[self.navigationcontroller pushviewcontroller:viewcontroller animated:YES];
threadStartAnimating:
-(void)threadStartAnimating:(id)data
{
[spinner startAnimating];
}