我有一个块来下载转换图像到UIImage。这是我的代码
-(UIImage *)GetProfileImage
{
NSString *strimgBaseUrl=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"BaseImageURL"];
NSString *strFilePath=[dm.dictUserProfile valueForKey:@"ImagePath"];
NSString *strImgURL=[NSString stringWithFormat:@"%@%@",strimgBaseUrl,strFilePath];
__block UIImage *imgProf=nil;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL *imageURL = [NSURL URLWithString:strImgURL];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
dispatch_async(dispatch_get_main_queue(), ^{
imgProf= image;
if(image!=nil){
imgProf=image;
}
});
});
return imgProf;
}
但是这个块永远不会执行。它会转到return
__block UIImage *imgProf=nil;
为什么会这样?请帮帮我。
由于
答案 0 :(得分:1)
代码工作正常。这是dispatch_async
的目的。
形成文档
@function dispatch_async
调用dispatch_async()总是在提交块后立即返回,并且永远不会等待块被 调用
这与dispatch_sync
相反。
您可以像这样更改GetProfileImage
- (void)setProfileImageForImageView:(UIImageView *)imageView {
NSString *strimgBaseUrl=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"BaseImageURL"];
NSString *strFilePath=[dm.dictUserProfile valueForKey:@"ImagePath"];
NSString *strImgURL=[NSString stringWithFormat:@"%@%@",strimgBaseUrl,strFilePath];
__block UIImage *imgProf=nil;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL *imageURL = [NSURL URLWithString:strImgURL];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
dispatch_async(dispatch_get_main_queue(), ^{
imgProf= image;
if(image!=nil){
// imgProf=image;
imageView.image = image;
}
});
});
}
答案 1 :(得分:0)
改为使用完成块,而不是从函数返回:
-(void)GetProfileImageWithCompletion:(void (^)(UIImage *profileImage))completionHandler
{
NSString *strimgBaseUrl=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"BaseImageURL"];
NSString *strFilePath=[dm.dictUserProfile valueForKey:@"ImagePath"];
NSString *strImgURL=[NSString stringWithFormat:@"%@%@",strimgBaseUrl,strFilePath];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL *imageURL = [NSURL URLWithString:strImgURL];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
dispatch_async(dispatch_get_main_queue(), ^{
if(image!=nil && completionHandler){
completionHandler(image);
}
});
});
}
并像这样使用:
[self GetProfileImageWithCompletion:^(UIImage *profileImage)
{
//if image exists assign to image view
}
];