2012-05-27 168 views
1

在我的iPhone应用程序中,我必须显示缩略图图像的预览。实际上,我们将从远程服务器获取该预览图像。在屏幕上加载大图像之前,我必须显示预加载视图,但实际上这个预加载视图并未出现在屏幕上。从远程服务器获取图像

我使用的代码是:

zoomview=[[UIView alloc]initWithFrame:CGRectMake(0,0,320,460)]; 
imageloadview.backgroundColor=[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.5]; 
[self.view addSubview:imageloadview]; 
[activity startAnimating]; 
[self loadimageview]; 

这里,而不是装在这个加载视图方法执行画面放大观看,但我想显示从服务器获取大图像之前预加载视图。

-(void)loadimageview 
{ 
    imageloader.image=[UIImage imageNamed:@""]; 

    [self loadimage]; 
} 

-(void)loadimage 
{ 
    NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:[picfullarray objectAtIndex:0]]]; 

    if([data length]==0) 
    { 
     NSLog(@"data"); 
    } 
    else 
    { 
     UIImage *image1=[UIImage imageWithData:data]; 
     imageloader.image=image1; 

     [activity stopAnimating]; 
     [loadlabel1 setText:@""]; 
    } 
} 

如何在从服务器获取大图像之前在iPhone屏幕上显示预装视图?

+0

http://stackoverflow.com/questions/9763979/download-image-asynchronously/9766123#9766123也许异步图像下载可能会帮助你.. –

回答

1

您必须加载图像与NSURLRequest异步。

使类实现NSURLRequestDelegate协议。在功能- (void)connectionDidFinishLoading:(NSURLConnection *)connectionNSURLRequestDelegate中,添加代码以在加载完成时更新视图。

// You must declare NSMutableData somewhere to write received data in delegate method 
// - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
// I assume the instance of NSMutableData is named data 

// If you want to load multiple images, it is a bit tricky, but doable. 
// I'll post the code if that is what you need. 

- (void) connectionDidFinishLoading: (NSURLConnection *) connection { 
    // You may want to declare a instance member to store the image (UIImage*), so that you can restore the view if the view is unloaded due to memory warning. 
    UIImage* image = [UIImage imageWithData: data]; 


    data = nil; // Important. You should clean the data, or it will take up space. 
    // You may want to check whether image != nil, since the incoming data may not be image 
    [self displayImage: image]; 
} 

- (void) displayImage: (UIImage*) aImage { 
    imageloader.image = aImage; 
    // Depending on how UIImageView is initialized, you may need to call sizeToFit. 
    // Or set the frame accordingly 

    [activity stopAnimating]; 
    [loadlabel1 setText: @""]; 
} 
+0

嗨谢谢你的回复。你能不能详细地提一下这个。如果有可能通过使用我在上面的帖子中提到的代码。感谢你。 –

+0

代码示例位于链接中。我只会添加更多不在链接中的内容,以便更清楚地说明您应该执行的操作。 – nhahtdh

+0

嗨谢谢,我需要提一个条件,实际上我有4个小图像,当用户点击一个图像时,我们必须在imageview中显示那个时间,我们必须遵循的方法。 –

0

我建议使用SDWebImage框架。它已经具有异步图像加载功能,而且使用起来非常简单。

[imageView.image setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] 
       placeholderImage:[UIImage imageNamed:@"placeholder.png"]]; 

您不必担心与NSURLConnection搞乱,保持NSData等。