UIActivityIndicatorView
由于您[NSData dataWithContentsOfURL:url]
在主线程上使用,您可能看不到。这会阻止主线程显示,UIActivityIndicatorView
直到图像下载完成,然后您将其删除。
您可能想要执行以下操作:
但请确保您在文件中定义spinner
了*.h
此功能。
- (void)viewDidLoad
{
...
//This code will make downloadImage run in the background thread
[self performSelectorInBackground:@(downloadImage) withObject:nil]
...
}
- (void) downloadImage{
NSLog(@"URL is:%@",urlString);
NSURL *url=[NSURL URLWithString:urlString];
UIImage *downloadedImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
//This code will make setImage run in the main thread since it is changing UI
[more_info_image performSelectorOnMainThread:@selector(setImage:) withObject:downloadedImage waitUntilDone:NO];
//This code will make stopAnimating run in the main thread since it is changing UI
[spinner performSelectorOnMainThread:@selector(stopAnimating) withObject:nil waitUntilDone:NO];
}
另一种方法是使用Grand Central Dispatch并执行以下操作:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
UIActivityIndicatorView *spinner=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
spinner.center=CGPointMake(160.0,240.0 );
spinner.hidesWhenStopped=YES;
[self.view addSubview:spinner];
[spinner startAnimating];
//This is the new GCD code
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
dispatch_async(queue, ^{
//This code will run on a background thread
NSString *urlString=[NSString stringWithFormat:@"http://mysite.com/projects/test/test.jpg"];
NSLog(@"URL is:%@",urlString);
NSURL *url=[NSURL URLWithString:urlString];
UIImage *downloadedImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
dispatch_sync(dispatch_get_main_queue(), ^{
//this code runs on the main thread since it is UI changes
[more_info_image setImage:downloadedImage];
[spinner stopAnimating];
});
});
}