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

最终效果图
使用了一个自定义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
@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
#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];
[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];
- (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{
}
[self showDownloadCompleteView:downloadBar msg:@"离线公交数据下载完成"];
}
- (void)downloadBar:(UIDownloadBar *)downloadBar didFailWithError:(NSError *)error{
[self showDownloadCompleteView:downloadBar msg:@"下载失败"];
}
- (void)downloadBarUpdated:(UIDownloadBar *)downloadBar{
}
-(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];
}
[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
分类:
手机开发(iPhone)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】