NSURL *url = [NSURL URLWithString:@"http://i0.kym-cdn.com/entries/icons/original/000/005/545/OpoQQ.jpg?1302279173"];
NSData *data = [NSData dataWithContentsOfURL:url];
imageView.image = [[[UIImage imageWithData:data];
我想在下载时设置进度条。
举一个更详细的例子:
在你的 .h 文件中做
@interface YourClass : YourSuperclass<NSURLConnectionDataDelegate>
在你的 .m 文件中做
@property (nonatomic) NSMutableData *imageData;
@property (nonatomic) NSUInteger totalBytes;
@property (nonatomic) NSUInteger receivedBytes;
在某处打电话
NSURL *url = [NSURL URLWithString:@"http://i0.kym-cdn.com/entries/icons/original/000/005/545/OpoQQ.jpg?1302279173"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
并实现委托方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) urlResponse;
NSDictionary *dict = httpResponse.allHeaderFields;
NSString *lengthString = [dict valueForKey:@"Content-Length"];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSNumber *length = [formatter numberFromString:lengthString];
self.totalBytes = length.unsignedIntegerValue;
self.imageData = [[NSMutableData alloc] initWithCapacity:self.totalBytes];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.imageData appendData:data];
self.receivedBytes += data.length;
// Actual progress is self.receivedBytes / self.totalBytes
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
imageView.image = [UIImage imageWithData:self.imageData];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//handle error
}
使用该方法无法获得进度回调。
您需要使用NSURLConnection
and NSURLConnectionDataDelegate
。
NSURLConnection
then 异步运行并将回调发送给它的委托。
主要看的是...
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
和
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
这些都用于获取连接以完成您已经在做的事情。
编辑
实际上,请参阅下面的 Marc 的回答。它是正确的。
您可以使用 MBProgress Hud 类来加载视图。您只能从此处下载两个类:- https://github.com/jdg/MBProgressHUD 在您要加载数据的类中编写此代码后示例:在您的 viewDidLoad 中您编写此代码
- (void) viewDidLoad
{
MBProgressHud *spinner = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
spinner.mode = MBProgressHUDModeCustomView;
[spinner setLabelText:@"Loading....."];
[spinner setLabelFont:[UIFont systemFontOfSize:15]];
[spinner show:YES];
[self performSelectorInBackground:@selector(getData) withObject:nil];
}
- (void) getData
{
NSURL *url = [NSURL URLWithString:@"http://i0.kym-cdn.com/entries/icons/original/000/005/545/OpoQQ.jpg?1302279173"];
NSData *data = [NSData dataWithContentsOfURL:url];
imageView.image = [[[UIImage imageWithData:data];
[spinner hide:YES];
[spinner removeFromSuperViewOnHide];
}