我正在app delegate类中异步下载json提要。现在,数据需要一段时间才能加载,因此我的表视图最初显示为空,几秒钟后填充。因此,我想:
1-找出造成延迟的原因。因此,保留应用程序中的所有活动:didffinishlaunchingwithoptions方法,并且只在加载所有内容后加载vc。
或
2-显示活动指示器,直到表填充数据。
现在,在第一个场景中,我确信我在错误的时间推动视图控制器。我试着玩它,但似乎这是唯一的方式,我的应用程序将建立和运行。
在第二个场景中,我想知道哪个“connection”方法首先被调用,哪个最后被调用。因此,我将能够在第一个方法启动activity indicator视图,并在最后一个方法结束时发布。
下面是我的代码。我们非常感谢您的任何建议/帮助。谢谢你的阅读。
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Error"
message:@"Please check your network connection and relaunch the application"
delegate:self
cancelButtonTitle:@"Dismiss"
otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
if ([responseString isEqualToString:@"Unable to find specified resource."]) {
NSLog(@"Unable to find specified resource.n");
}
else {
ListingsViewController *listingsViewController = [[ListingsViewController alloc] initWithNibName:@"ListingsViewController" bundle:nil];
listingsViewController.jsonData = responseString;
[self.navigationController pushViewController:listingsViewController animated:NO];
[self.navigationController setViewControllers:[NSArray arrayWithObject:listingsViewController] animated:NO];
[listingsViewController release];
}
[connection release];
[responseData release];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Start the HTTP request
responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:
[NSURL URLWithString:@"http://www.shoofeetv.com/iphonexml/view/all_channels.json"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
// Display the navigation controller
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];
return YES;
}
最佳答案
选择2。尽可能快地显示东西是一个很好的ui设计,尽管ui在数据加载之前可能没有用处,但它至少会让应用程序的用户感觉到发生了什么事情。
在DidFinishLaunchingWithOptions中弹出用户界面,显示活动指示器,并在连接中隐藏和销毁活动指示器。
我还建议将所有异步http请求逻辑包装到另一个类中,并让它接受委托,然后可以调用:
{
// Show activity indicator
[httpClient get:@"www.example.com/json" withDelegate:self];
}
-(void)httpClientSuccessful:(NSData*)response
{
// hide activity indicator
}