UIImageView加载图像非常慢

时间:2014-09-18 21:48:14

标签: ios objective-c xcode uiimageview nsurlsession

我有一些代码可以从网页获取图像并将其显示在ImageView中。但由于某种原因,我的图像加载非常慢,我真的不懂!通过我的日志记录,我可以看到图像的所有数据(base64字符串)很快到达,但图像在ImageView中显示大约需要12-15秒。

我发现这很奇怪,因为我使用NSStream以不同的方法获取图像的数据,并在所有数据到达时立即加载图像。但是使用这种URLSession方法,加载图像需要更长的时间。这真的没有意义!此方法不应影响ImageView加载数据的方式。

有人想知道为什么会这样吗?

继承人代码:

- (void)postMethod:(NSDictionary *)numDict
{
NSURL *url = [NSURL URLWithString:@"http://theWebAddress.com/aPage.php"]; // add url to page
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = @"POST";


NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:numDict options:kNilOptions error:&error];

NSLog(@"%@", numDict);

if (!error)
{
    NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        NSDictionary *diction = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];


        for (id key in diction)
        {
            if ([key isEqualToString:@"text"])
            {
                NSLog(@"data is text");

                self.messageLabel.text = diction[@"text"];

                break;
            }
            else if ([key isEqualToString:@"image"])
            {
                NSLog(@"data is an image");

                // gets the base64 string pretty instantly but takes 12 - 15 seconds to pop up in the imageView

                NSData *ImgData = [[NSData alloc] init];
                ImgData = [[NSData alloc] initWithBase64EncodedString:diction[@"image"] options:1];

                self.ImageView.image = [UIImage imageWithData:ImgData];

                break;
            }
        }

    }];

    [uploadTask resume];
}
}
非常感谢!

3 个答案:

答案 0 :(得分:8)

您的完成处理程序可能正在后台线程上运行。 UI更新应始终适用于主线程。在

处设一个断点
self.ImageView.image = [UIImage imageWithData:ImgData]; 

并查看它是否在主线程上。如果没有,请在设置ImageView.image之前将其分配给主线程:

dispatch_async(dispatch_get_main_queue(), ^{
    self.ImageView.image = [UIImage imageWithData:ImgData];
});

答案 1 :(得分:2)

您可以尝试使用SDWebImage https://github.com/rs/SDWebImage,您只需要在imageView中设置图像,如下所示:

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

答案 2 :(得分:0)

您首先下载图像然后显示图像。您可以使用延迟加载下载图像。

为此你可以使用EgoImageView而不是uiimageview。

self.ImageView.imageURL = [NSURL URLWithString:

这里self.ImageView是egoimageview类型。

你可以从github获得这个课程。

https://github.com/enormego/EGOImageLoading