您如何下载一张图片并将其转换为UIImage?
您如何下载一张图片并将其转换为UIImage?
NSURL *url = [NSURL URLWithString:@"http://example.com/image.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[[UIImage alloc] initWithData:data] autorelease];
然而,这并不是异步的。
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (requestData)
{
self.image = [[[UIImage alloc] initWithData:requestData] autorelease];
}
}
requestData
和image
是您所包含的类的实例变量,且image
是一个保留属性。请确保在类的dealloc
过程中释放image
,例如使用self.image=nil;
。
dispatch_async
简单地从URL加载UIImageView
中的图像,而不会阻塞UI线程:dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL *url = [NSURL URLWithString:myURL];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage* image = [[UIImage alloc]initWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
[myImageView setImage:image];
});
});
第一个dispatch_async
用于在后台加载图像(而不会阻塞UI)。第二个dispatch_async
用于将刚刚加载的图像注入到UIImageView
中。请注意,第二个dispatch_async
被设计为在主线程(即更新UI的线程)上运行。
虽然异步加载确实必要,但如果只需要简单的解决方案,您也可以通过后台调用来实现。
[self performSelectorInBackground:@selector(loadImage) withObject:nil];
- (void)loadImage
{
NSURL * url = [NSURL URLWithString:@"http://.../....jpg"];
NSData * data = [NSData dataWithContentsOfURL:url];
UIImage * image = [UIImage imageWithData:data];
if (image)
{
// Success use the image
...
}
else
{
// Failed (load an error image?)
...
}
}
这里有一个非常好的例子,使用块来简化获取URL中的UIImage:http://ios-blog.co.uk/iphone-development-tutorials/uiimage-from-url-%E2%80%93-simplified-using-blocks/
根据 @philfreo 的回答,我使用 BrightFutures 在 Swift 中创建了一个 NSURL 扩展来进行异步回调:
extension NSURL{
func downloadImage() -> Future<UIImage, NSError>{
let promise = Promise<UIImage, NSError>()
Queue.global.async{
if let data = NSData(contentsOfURL: self){
if let image = UIImage(data: data){
promise.success(image)
return
}
}
promise.failure(NSError())
}
return promise.future
}
}
import BrightFutures
let someURL = ...;
someURL.downloadImage().onSuccess{ image in
// Do something with the UIImage
}
一个简单的同步扩展可以像这样:
extension NSURL{
func downloadImage() -> UIImage?{
if let data = NSData(contentsOfURL: self){
return UIImage(data: data){
}
return nil
}
}