UIImageView加载图像很慢
我有一些代码从网页获取图像并将其显示在ImageView中。但由于某种原因,图像加载非常缓慢,我不太明白!通过我的日志记录,我可以看到图像的所有数据(base64字符串)都很快到达,但图像出现在ImageView中需要大约12到15秒。UIImageView加载图像很慢
我觉得这很奇怪,因为我使用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];
}
}
非常感谢!
你完成处理程序可能会在后台线程进行操作。 UI更新应始终在主线程上运行。把一个断点在
self.ImageView.image = [UIImage imageWithData:ImgData];
看看它是否在主线程。如果没有,请在设置ImageView.image之前将其发送到主线程:
dispatch_async(dispatch_get_main_queue(), ^{
self.ImageView.image = [UIImage imageWithData:ImgData];
});
就像一个魅力!尽管你的代码在第一个{'dispatch_async(dispatch_get_main_queue(),^ {code})之前丢失了^; ' 非常感谢! – ThriceGood 2014-09-19 17:39:29
是的,谢谢你的提示。在SO中写了一个快速的答案,而不是xcode,所以我没有抓住它。 – mitrenegade 2014-09-19 17:54:34
您首先要下载图片,然后显示图片。您可以使用延迟加载下载图片。
为此,您可以使用EgoImageView而不是uiimageview。
self.ImageView.imageURL = [NSURL URLWithString:
这里self.ImageView是egoimageview类型。
你可以从github上得到这个类。
你可以尝试使用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"]];
为什么使用上传任务? – 2014-09-18 21:51:05
因为我发布了一些数据到网页上,那么页面会根据这些数据输出文本或图像。 – ThriceGood 2014-09-18 22:56:57