---
title: "Download, Create and Display an Image from URL"
author: "xinlanzero"
date: "2011-07-22T13:39:46Z"
tags: []
categories: ["移动开发"]
slug: "download-create-and-display-an-image-from-url"
draft: false
lastmod: "2011-07-22T13:39:46Z"
id: 1130617
url: "https://xinlanzero.iteye.com/blog/1130617"
---

Posted on November 4, 2009 by [John Muchow](http://iphonedevelopertips.com/author/admin "Posts by John Muchow") in [Cocoa](http://iphonedevelopertips.com/category/cocoa "View all posts in Cocoa")

[Tweet](http://twitter.com/share) &lt;script src="http://platform.twitter.com/widgets.js" type="text/javascript"&gt;&lt;/script&gt;&lt;!-- &lt;a target="\_blank" href="http://iPhoneDeveloperTips.com?wp\_ct=10"&gt;&lt;img border="0" src="/images/ads/SnowLeopard.jpg"&gt;&lt;/a&gt;&lt;img src="http://www.assoc-amazon.com/e/ir?t=iphonedevelopertips-20&l=as2&o=1&a=B001AMPP0W" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /&gt; --&gt;

&lt;!-- Ad in post --&gt;&lt;!-- &lt;div style="float: left; width: 169; height: 76; margin:0px 0px 0px 0px;"&gt; &lt;a href="http://iPhoneDeveloperTips.com?wp\_ct=37"&gt;&lt;img border="0" src="/images/ads/job-board-ad-link-in-post.png"&gt;&lt;/a&gt; &lt;/div&gt; --&gt;&lt;!--content with more link--&gt;

 

This tip will show the steps to download and display an image from a remote resource. This is handy if you need to add an image as a subview, yet, the image is not part of your application bundle.

##### URL to Remote Image

We start by creating a URL to the remote resource:

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

##### Create UIImage from NSData

The next step is to build a **UIImage** using the data downloaded from the URL, which consists of an **NSData** object that holds the remote image contents:

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

##### Putting it Together

Here’s how to wrap it all together, adding the remote image as a subview to an existing view by creating a **UIImageView** from the above **UIImage**:

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