2012-05-27 272 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等。