gpt4 book ai didi

ios - 使用 grand central dispatch 下载 UIImage

转载 作者:行者123 更新时间:2023-11-28 18:33:25 25 4
gpt4 key购买 nike

我有一个 URL,当它被复制到浏览器时,会显示一个图像。我的函数应该异步下载图像。

- (UIImage *)downloadImage:(NSString *)imageURL
{
NSError *error = nil;
NSURL *urlString = [NSURL URLWithString:imageURL];
NSData *data = [NSData dataWithContentsOfURL:urlString options:NSDataReadingUncached error:&error];
__block UIImage *image;

if (!error) {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
image = [UIImage imageWithData:data];
});
return image;
} else {
NSLog(@"%@", [error localizedDescription]);
}
return nil;
}

当我尝试在 UIImageView 中显示图像时,我没有收到任何错误,什么也没有。我已经通过 NSLogged 输出了 dataimageURL,它们都不是空的。

有什么建议吗?

最佳答案

通过调用 dispatch_async,您可以安排该工作稍后发生。在该工作完成之前,您的函数以 nil 退出。您需要向您的函数添加一个回调 block 或使其阻塞,直到您接收并处理图像数据。

这是一个带有 block 回调函数的示例以及如何使用它。

- (void)downloadImageAtURL:(NSString *)imageURL withHandler:(void(^)(UIImage *image))handler
{
NSURL *urlString = [NSURL URLWithString:imageURL];

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:urlString options:NSDataReadingUncached error:&error];
if (!error) {
UIImage *downloadedImage = [UIImage imageWithData:data];
handler(downloadedImage); // pass back the image in a block
} else {
NSLog(@"%@", [error localizedDescription]);
handler(nil); // pass back nil in the block
}
});
}



- (void)keyboardDidShow:(NSNotification *)aNotification {
[self downloadImageAtURL:@"" withHandler:^(UIImage *image) {
if (image) {
// display
} else {
// handle probelm
}
}];
}

关于ios - 使用 grand central dispatch 下载 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23638589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com