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"];//同理也有old如果你传了的话 float ff= [nuber floatValue]; NSLog(@"%.1f%%",ff*100); }
//说明一下这个属性keyPath就是指监听的属性,object就是指的监听的是哪个对象的属性,change里面放的就是一些改变值,context就是你注册监听的时候传的什么就是什么
心得,异步请求都是有个请求队列的,就像gcd一样,线是穿件一个线程,再到线程里面创建一个请求队列,再往请求队里里面丢要执行的事情(包括request),当然这里的组合就随机了,你可以是有个请求(request),丢到一个默认的队列里面去执行就是了,队列可以控制最大并发数量。
你也可以有个队列(queue),在往队列里丢请求或者其他