在viewDidLoad中显示UIActivityIndi​​cator

时间:2012-12-26 16:20:27

标签: objective-c ios uiactivityindicatorview

我正在开发一个应用程序,它通过JSON从Web服务器获取数据到UITableViewController

加载数据需要时间,因此我希望在viewDidLoad的加载时间内显示微调器。

这是我的第一个申请,所以我需要更多介绍一下如何做到这一点。

viewDidLoad方法

- (void)viewDidLoad
{
    [super viewDidLoad];


    NSString *categoryId = catId;
    NSString *post =[NSString stringWithFormat:@"categoryId=%@",categoryId];
    NSString *cat = [NSString stringWithFormat:@"&cityId=%@",cityId];
    NSString *hostStr = @"http://localhost:8888/iphone-so/bycategory.json.php?";
    hostStr = [hostStr stringByAppendingString:post];
    hostStr = [hostStr stringByAppendingString:cat];

    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:hostStr]];
    NSError *error;
    productsRaw = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    products = [productsRaw objectForKey:@"products"];
    productKeys = [products allKeys];
}

2 个答案:

答案 0 :(得分:0)

您可以使用MBProgressHUD只需将MBProgressHUD.h和MBProgressHUD.m文件添加到您的项目中(如果您启用了ARC,则可能需要转换为ARC)

    // Add right after your [super viewDidLoad]; ] your start connection method or in viewdidload whatever....
- (void)viewDidLoad
{
    [super viewDidLoad];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"Loading...";

     // rest of the code goes here
}


// Add at start of requestFinished AND requestFailed
[MBProgressHUD hideHUDForView:self.view animated:YES];

答案 1 :(得分:0)

- (void)viewDidLoad
{
    [super viewDidLoad];

    // create the activity indicator
    UIActivityIndicator *indicator = [UIActivityIndicator alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGrey];

    // add it
    [self.view addSubview:indicator];

    // animate it
    [indicator startAnimating];

    // your code
    NSString *categoryId = catId;
    NSString *post =[NSString stringWithFormat:@"categoryId=%@",categoryId];
    NSString *cat = [NSString stringWithFormat:@"&cityId=%@",cityId];
    NSString *hostStr = @"http://localhost:8888/iphone-so/bycategory.json.php?";
    hostStr = [hostStr stringByAppendingString:post];
    hostStr = [hostStr stringByAppendingString:cat];

    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:hostStr]];
    NSError *error;
    productsRaw = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    products = [productsRaw objectForKey:@"products"];
    productKeys = [products allKeys];

    // stop animating the indicator
    [indicator stopAnimating];
}