iphone下载进度条,显示下载字节数与百分比

原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://yuyi123.blog.51cto.com/1987900/504457

最终效果图
使用了一个自定义uiview,里面加入了一个progressbar和两个label,
头文件
#import <UIKit/UIKit.h>
@protocol UIDownloadBarDelegate;

@interface UIDownloadBar : UIView {
  UIProgressView *progressView;
  NSURLRequest* DownloadRequest;
  NSURLConnection* DownloadConnection;
  NSMutableData* receivedData;
  NSString* localFilename;
  id<UIDownloadBarDelegate> delegate;
  long long bytesReceived;
  long long expectedBytes;
  
  float percentComplete;
  UILabel *lblDownloadBytes;
  UILabel *lblDownloadPercent;
}
@property (nonatomic, readonly) NSMutableData* receivedData;
@property (nonatomic, readonly, retain) NSURLRequest* DownloadRequest;
@property (nonatomic, readonly, retain) NSURLConnection* DownloadConnection;
@property (nonatomic, assign) id<UIDownloadBarDelegate> delegate;
@property (nonatomic, readonly) float percentComplete;
- (UIDownloadBar *)initWithURL:(NSURL *)fileURL 
         progressBarFrame:(CGRect)frame 
                timeout:(NSInteger)timeout 
             delegate:(id<UIDownloadBarDelegate>)theDelegate;
@end

@protocol UIDownloadBarDelegate<NSObject>

@optional
- (void)downloadBar:(UIDownloadBar *)downloadBar didFinishWithData:(NSData *)fileData suggestedFilename:(NSString *)filename;
- (void)downloadBar:(UIDownloadBar *)downloadBar didFailWithError:(NSError *)error;
- (void)downloadBarUpdated:(UIDownloadBar *)downloadBar;

@end
实现类
#import "UIDownloadBar.h"
#import <QuartzCore/QuartzCore.h>

@implementation UIDownloadBar
@synthesize DownloadRequest,DownloadConnection,receivedData,delegate,percentComplete;

- (UIDownloadBar *)initWithURL:(NSURL *)fileURL progressBarFrame:(CGRect)frame timeout:(NSInteger)timeout delegate:(id<UIDownloadBarDelegate>)theDelegate {
  self = [super initWithFrame:frame];
  if(self) {
    self.layer.borderWidth = 2.0;
    self.layer.cornerRadius = 5.0;
    self.layer.borderColor = [UIColor whiteColor].CGColor;
    self.backgroundColor = [UIColor blackColor];
    //进度条,中间
    progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleBar];
    progressView.frame = CGRectMake(10, 20, self.frame.size.width-20, 20);
    [self addSubview:progressView];
    //左下角
    CGRect lblDownloadBytesFrame = CGRectMake(10, frame.size.height-35, 120, 20);
    lblDownloadBytes = [[UILabel alloc]initWithFrame:lblDownloadBytesFrame];
    lblDownloadBytes.textColor = [UIColor whiteColor];
    lblDownloadBytes.backgroundColor = [UIColor clearColor];
    [self addSubview:lblDownloadBytes];
    //右下角
    CGRect lblDownloadPercentFrame = CGRectMake(frame.size.width-50
                          , frame.size.height-35, 60, 20);
    lblDownloadPercent = [[UILabel alloc]initWithFrame:lblDownloadPercentFrame];
    lblDownloadPercent.textColor = [UIColor whiteColor];
    lblDownloadPercent.backgroundColor = [UIColor clearColor];
    [self addSubview:lblDownloadPercent];
    
    
    self.delegate = theDelegate;
    lblDownloadPercent.text = @"0%";
    bytesReceived = percentComplete = 0;
    localFilename = [[[fileURL absoluteString] lastPathComponent] copy];
    receivedData = [[NSMutableData alloc] initWithLength:0];
    progressView.progress = 0.0;
    progressView.backgroundColor = [UIColor clearColor];
    DownloadRequest = [[NSURLRequest alloc] initWithURL:fileURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:timeout];
    DownloadConnection = [[NSURLConnection alloc] initWithRequest:DownloadRequest delegate:self startImmediately:YES];
    
    if(DownloadConnection == nil) {
      [self.delegate downloadBar:self didFailWithError:[NSError errorWithDomain:@"UIDownloadBar Error" code:1 userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"NSURLConnection Failed", NSLocalizedDescriptionKey, nil]]];
    }
  }
  
  return self;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
  [self.receivedData appendData:data];
  
  NSInteger receivedLen = [data length];
  bytesReceived = (bytesReceived + receivedLen);
  lblDownloadBytes.text = [NSString stringWithFormat:@"%.02f/%.02fMB",
            (float)bytesReceived/1048576,(float)expectedBytes/1048576];
  //百分比
  lblDownloadPercent.text = [NSString stringWithFormat:@"%.0f%%",
                    (((float)bytesReceived/1048576)/((float)expectedBytes/1048576))*100];
  if(expectedBytes != NSURLResponseUnknownLength) {
    progressView.progress = ((bytesReceived/(float)expectedBytes)*100)/100;
    percentComplete = progressView.progress*100;
  }
  
  [delegate downloadBarUpdated:self];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
  [self.delegate downloadBar:self didFailWithError:error];
  [connection release];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
  expectedBytes = [response expectedContentLength];
  lblDownloadBytes.text = [NSString stringWithFormat:@"0/%.02fMB",(float)expectedBytes/1048576];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
  [self.delegate downloadBar:self didFinishWithData:self.receivedData suggestedFilename:localFilename];
  [connection release];
}

- (void)drawRect:(CGRect)rect {
  [super drawRect:rect];
}

- (void)dealloc {
  [progressView release];
  [localFilename release];
  [receivedData release];
  [DownloadRequest release];
  [DownloadConnection release];
  [lblDownloadBytes release];
  [lblDownloadPercent release];
  [super dealloc];
}
@end
调用方式
self.userInteractionEnabled = NO;
    [self addSubview:mask];
    UIDownloadBar *downloadBar = [[UIDownloadBar alloc]initWithURL:[NSURL URLWithString:selectedCity.dbpath]
                             progressBarFrame:CGRectMake(50, 130, 220, 80) 
                                    timeout:5 
                                 delegate:self];
    [self addSubview:downloadBar];
注意要实现delegate的三个方法
- (void)downloadBar:(UIDownloadBar *)downloadBar didFinishWithData:(NSData *)fileData suggestedFilename:(NSString *)filename{
  [self showDownloadCompleteView:downloadBar msg:@"离线公交数据下载完成"];
}

- (void)downloadBar:(UIDownloadBar *)downloadBar didFailWithError:(NSError *)error{
  [self showDownloadCompleteView:downloadBar msg:@"下载失败"];
}

- (void)downloadBarUpdated:(UIDownloadBar *)downloadBar{
  
}
可以用一个label提示下载成功或者失败
-(void)showDownloadCompleteView:(UIDownloadBar*)downloadBar msg:(NSString*)message{
  [mask performSelector:@selector(removeFromSuperview) 
            withObject:nil 
            afterDelay:1.5];
  [UIView animateWithDuration:2 
            animations:^{
             downloadBar.alpha = 0;
            }];
  [downloadBar performSelector:@selector(removeFromSuperview) 
             withObject:nil 
             afterDelay:2];
  self.userInteractionEnabled = YES;
  UILabel *successAlert = [[UILabel alloc]initWithFrame:
                CGRectMake(60, 250, 200, 40)];
  successAlert.textColor = [UIColor whiteColor];
  successAlert.backgroundColor = [UIColor lightGrayColor];
  successAlert.layer.borderColor = [UIColor whiteColor].CGColor;
  successAlert.layer.cornerRadius = 5;
  successAlert.layer.borderWidth = 2.0;
  successAlert.textAlignment = UITextAlignmentCenter;
  successAlert.text = message;
  [self addSubview:successAlert];
  //慢慢变透明,然后消失
  [UIView animateWithDuration:2 
            animations:^{
             successAlert.alpha = 0;
            }];
  [successAlert performSelector:@selector(removeFromSuperview)
                withObject:nil 
                afterDelay:2];
}

本文出自 “iphone开发” 博客,请务必保留此出处http://yuyi123.blog.51cto.com/1987900/504457

原文地址:https://www.cnblogs.com/zhwl/p/2874777.html