ios - 设置下载NSData的进度条

标签 ios xcode4.5

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

同时实现委托(delegate)方法

- (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
}

关于ios - 设置下载NSData的进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19831885/

相关文章:

objective-c - Xcode4.5 汇编程序无法编译 Xcode4.4 完美处理的文件

xamarin.ios - 使用 MonoTouch 部署 IOS6 应用程序时出错

ios - 如何在 swift 中添加新键但不向字典添加值?

c++ - 在 xcode 中链接 boost 库

xcode4.5 - 当 IOS 7 启动时,为 ios 6 构建的所有应用程序看起来都很好吗?

iphone - 缺少'@end'//@end必须出现在Objective-C上下文中

iphone - 如何以编程方式绘制边框并在 UIImageview 周围的单词后将其删除?

ios - UILabel Padding 基于内容

ios - 有什么方法可以列出 iOS 应用程序中的所有 swizzled 方法吗?

ios - 如何从url下载视频并将其保存到iOS中的文档目录?