下午好,我在使用“活动指示器”时遇到了困难,我希望它在我将XML下载到NSData时出现在我的视图中,当下载完成后它变得不可见。
尝试过,但只有在下载完成后才会显示指示符。
我使用的代码很简单,启动“活动指示器”调用服务器URL,转移到NSData然后停止“活动指示器”并调用另一个在WebView中显示信息的View,即“活动指示器“开始加载,我希望显示在加载WebView之前出现。
答案 0 :(得分:1)
您需要在不同的线程(不是主线程)上下载。最好的方法是使用GCD。以下是示例代码:
//Start Activity indicator on the main thread,
[activityIndicator performSelectorOnMainThread:@selector(startAnimating) withObject:nil waitUntilDone:YES];
dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Start Download code
dispatch_async( dispatch_get_main_queue(), ^{
[activityIndicator stopAnimating];
});
});
答案 1 :(得分:0)
这是UIActivityIndicatorView的一个示例。它在开始下载之前启动微调器,并在调用块的完成处理程序时停止微调器。请记住仅从主队列更新UI - 在这种情况下停止微调器。
-(void)test
{
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[activityIndicator setCenter:CGPointMake(screenWidth/2.0, screenHeight/2.0)];
[self.view addSubview:activityIndicator];
[activityIndicator startAnimating];
NSMutableString *myURL = [[NSMutableString alloc] initWithString:@"http://www.domain.com/"];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:[myURL stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection
sendAsynchronousRequest:urlRequest
queue:queue
completionHandler: ^( NSURLResponse *response,
NSData *data,
NSError *error)
{
if (error == nil)
{
// do whatever with data
dispatch_async(dispatch_get_main_queue(), ^{
[activityIndicator stopAnimating]; // stop spinner from the main queue
[activityIndicator removeFromSuperview];
});
} else // got an error
{
dispatch_async(dispatch_get_main_queue(), ^{
[activityIndicator stopAnimating]; // stop spinner from the main queue
[activityIndicator removeFromSuperview];
});
}
}];
}