我对objective-c有点新,我正在开发一个新闻iOS应用程序,该应用程序使用来自URL的JSON解析获取其所有内容,我使用AFNetworking
为此,这是我做的方法:
- (void)getContents
{
NSString *urlString = @"http://some-url-that-has-json-output/";
urlString = [urlString stringByAppendingString:self.articleId];
NSLog(@"The call url is: %@",urlString);
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//AFNetworking asynchronous url request
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"The JSON data is: %@", responseObject);
jsonContents = [responseObject objectForKey:@"article"];
[self LoadStructure];
} failure:nil];
[operation start];
}
现在,使用此方法可以很好地加载数据。
我的问题:如何在获取数据时显示加载指示符(可能是GIF)?以上这种方法是从网址获取数据的正确或最佳方法吗?
答案 0 :(得分:1)
您可以使用iOS的默认加载指示符(UIActivityIndicator)。您应该在完成块之前开始设置动画,并且应该隐藏在成功和失败块中。
您应该使用指标作为类变量创建一个方法:
indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
indicator.hidesWhenStopped = YES;
indicator.frame = CGRectMake(35, 15, 30, 30);
[self.view addSubview:indicator];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//AFNetworking asynchronous url request
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[indicator startAnimating];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"The JSON data is: %@", responseObject);
//停止:
[indicator stopAnimating];
jsonContents = [responseObject objectForKey:@"article"];
[self LoadStructure];
} failure::^(AFHTTPRequestOperation *operation, NSError *error){
[indicator stopAnimating];
}];
[operation start];
答案 1 :(得分:1)
将UIActivityIndicatorView
拖放到XIB视图中,并将其与IBOutlet连接。
.h文件
@property(nonatomic, strong)IBOutlet UIActivityIndicatorView * activityIndicator;
在视图中添加UIActivity指示器视图。在
之前展示 NSString *urlString = @"http://some-url-that-has-json-output/";
使用:[self.activityIndicator startAnimating];
并在完成块和故障块中停止
使用:[self.activityIndicator stopAnimating];