Download, Create and Display an Image from URL

Posted on November 4, 2009 by John Muchow in Cocoa

<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]];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值