ITeye博客

Download, Create and Display an Image from URL

xinlanzero · 2011-07-22 13:39 · iPhone · 移动开发 · Markdown

Posted on November 4, 2009 by John Muchow in Cocoa

Tweet <script src="http://platform.twitter.com/widgets.js" type="text/javascript"></script><!-- <a target="_blank" href="http://iPhoneDeveloperTips.com?wp_ct=10"><img border="0" src="/images/ads/SnowLeopard.jpg"></a><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;" /> -->

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

 

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]];

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。