UIProgressView *uiprogressview= [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleBar];//建立一个进度条 uiprogressview.frame=CGRectMake(50, 100, 200, 20); uiprogressview.tag=10; [self.window addSubview:uiprogressview]; //通过观察者模式来检测这个属性 [uiprogressview addObserver:self forKeyPath:@"progress" options:NSKeyValueObservingOptionNew context:nil]; NSString * fileurlstring=@"http://free2.macx.cn:81/tools/system/CleanMyMac-v1-10-8.dmg"; NSString *downloadpath=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; NSString *filename=[fileurlstring lastPathComponent]; NSString *downloadpath_now= [downloadpath stringByAppendingPathComponent:filename]; ASIHTTPRequest*request= [[ASIHTTPRequest alloc]initWithURL:[NSURL URLWithString:fileurlstring]]; [request setDownloadDestinationPath:downloadpath_now];//设置存储路径 [request setDownloadProgressDelegate:[self.window viewWithTag:10]];//绑定一个进度条 [request setHeadersReceivedBlock:^(NSDictionary *responseHeaders) { NSLog(@"%@",responseHeaders);//里面包含了数据大小的那些内容 }];//当服务器做出响应后调用的block,返回的一个响应头,同理有请求头 [request startAsynchronous];//启动异步下载
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ NSLog(@"%@",keyPath); NSNumber *nuber= [change objectForKey:@"new"]; float ff= [nuber floatValue]; NSLog(@"%.1f%%",ff*100); }