インターネットから取得した画像を画面に表示したい。NSURLConnection を使用してデータを取得する非同期呼び出しを作成し、応答ブロックでコードを呼び出してそれを UIImage オブジェクトに割り当てました。
私の質問は、ブロックの実行後に sleep(1) を呼び出す必要があるのはなぜですか? 呼び出していない場合、画像は画面に描画されません。これを達成するための別のよりエレガントな方法はありますか?
-(void)loadImage:(NSString *)url
{
NSURL *imageURL = [NSURL URLWithString:url];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
NSURLRequest *imageRequest = [NSURLRequest requestWithURL:imageURL cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:5.0f];
[NSURLConnection sendAsynchronousRequest:imageRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if(!connectionError) {
if(data) {
//there goes the main thingy
self.myView.wallpaperImage = [UIImage imageWithData:data];
[self.myView setNeedsDisplay];
} else {
NSLog(@"No data found at url:%@",url);
}
} else {
NSLog(@"Could not connect to %@",url);
}
}];
sleep(1);
}