2013-02-08 72 views
-1

如何将图像下载到应用程序中?就像我想从我的网站获取图片并将其下载到该人的iPhone应用程序中以显示在应用程序中?基本上这个图像不会被url显示。如何将图像下载到应用程序中?

更具体:

如何将图像下载到应用程序,而无需使用UIImage的。我想获取图像并将其下载为文件名“anne.png”,然后使用UIImage将其作为anne.png引用到整个应用程序中。请参阅 - 我想先下载它,这样当有人第二次访问应用程序时,他们会看到图像,并在此期间看到默认图像。谢谢。?

+5

[你尝试过什么?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) – 2013-02-08 21:51:39

回答

0

对于单张图像,您可以使用以下内容。请记住,这将阻止用户界面直到图像被完全下载。

[UIImage imageWithData:[NSData dataWithContentsOfURL:photoURL]]; 

为了不阻塞UI下载图片:

dispatch_queue_t downloadQueue = dispatch_queue_create(“image downloader”, NULL); 

dispatch_async(downloadQueue, ^{ 
    [NSData dataWithContentsOfURL:photoURL]; 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     UIImage *image = [UIImage imageWithData:imageData]; 
     // Code to show the image in the UI goes here 
    }); 
}); 

将图像保存到你可以使用UIImageWriteToSavedPhotosAlbum手机相机胶卷。

将图像保存在应用程序的目录中。使用的NSData的writeToFile:atomically:

为了从网站下载一些图片,也许这可以帮助你:

What's the best way to download multiple images and display multiple UIImageView?

+0

如何将图像下载到该应用程序不使用UIImage。我想获取图像并将其下载为文件名“anne.png”,然后使用UIImage将其作为anne.png引用到整个应用程序中。请参阅 - 我想先下载它,以便当有人第二次访问应用程序时,他们会看到图像。谢谢。? – Jasmine 2013-02-08 23:07:05

+0

@BamBam正如我上面所建议的那样,在拥有'NSData'之后,你可以通过'writeToFile'来将其保存到永久存储中。 – Rob 2013-02-08 23:21:33

0

http://mobiledevelopertips.com/cocoa/download-and-create-an-image-from-a-url.html

URL到远程图像

我们开始通过创建一个URL到远程资源:

NSURL *url = [NSURL URLWithString: @"http://mobiledevelopertips.com/images/logo-iphone-dev-tips.png"]; 

从NSData的

下一步是生成使用从URL下载的数据一个UIImage,它由包含远程图像内容的NSData对象的创建的UIImage:

UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]]; 

将其组合在一起

以下是如何包裹它一起,加入远程图像作为一个子视图到现有的视图通过创建一个UIImageView FR OM以上的UIImage:

NSURL *url = [NSURL URLWithString:@"http://mobiledevelopertips.com/images/logo-iphone-dev-tips.png"]; 
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]]; 
    [self.view addSubview:[[UIImageView alloc] initWithImage:image]]; 
+0

但它阻止?如果阻塞,我该怎么办?这会将图像下载到个人的应用程序存储? – Jasmine 2013-02-08 22:00:15

+0

你试过这个吗?它被封锁了吗? – Garry 2013-02-08 22:01:22

+0

@BamBam您通常会在后台队列中执行第一步和第二步,并仅执行UI更新,即将主题“放在一起”。 – Rob 2013-02-08 22:46:17

相关问题