Thr*_*ood 2 xcode objective-c uiimageview ios 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];
}
}
Run Code Online (Sandbox Code Playgroud)
非常感谢!
您的完成处理程序可能正在后台线程上运行.UI更新应始终适用于主线程.把断点放在
self.ImageView.image = [UIImage imageWithData:ImgData];
Run Code Online (Sandbox Code Playgroud)
并查看它是否在主线程上.如果没有,请在设置ImageView.image之前将其分派到主线程:
dispatch_async(dispatch_get_main_queue(), ^{
self.ImageView.image = [UIImage imageWithData:ImgData];
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1995 次 |
| 最近记录: |