gho*_*der 1 lazy-loading spinner ios
当从一个视图移动到另一个视图时,我想在我的第二个视图中,只要下载图像以查看微调器(这样第二个视图将立即打开而不需要任何时间,并且用户等待微调器完).
这是我的代码:
在第二个视图中,打开的视图:
- (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];
NSString *urlString=[NSString stringWithFormat:@"http://mysite.com/projects/test/test.jpg"];
NSLog(@"URL is:%@",urlString);
NSURL *url=[NSURL URLWithString:urlString];
[more_info_image setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:url]]];
[spinner stopAnimating];
}
Run Code Online (Sandbox Code Playgroud)
我根本看不到旋转器.我不认为这是因为我的互联网连接太胖了.另一方面,当按下按钮并等待视图打开时,我看到一点延迟 - 就像它试图下载图像的时候一样.
我想打开视图,拥有微调器,下载图像然后让微调器消失.
我必须改变什么吗?
你可能没有看到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];
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用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];
});
});
}
Run Code Online (Sandbox Code Playgroud)