从远程服务器获取映像

时间:2012-05-27 05:07:00

标签: iphone objective-c uiview uiimageview

在我的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屏幕上显示预加载的视图?

3 个答案:

答案 0 :(得分:1)

您必须使用NSURLRequest异步加载图片。

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

// 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: @""];
}

答案 1 :(得分:0)

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

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

您不必担心弄乱NSURLConnection,维护NSData等等。

答案 2 :(得分:0)

还有AFNetworking可以轻松实现这一目标。

https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking

查看“下载和显示图像”部分。