1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| #import "ViewController.h" #import "DACircularProgressView.h" @interface ViewController ()<NSURLConnectionDataDelegate> @property(nonatomic,strong) NSMutableData *fileData; @property(nonatomic,assign) long long totalLength; //文件的长度 @property (weak, nonatomic) IBOutlet UIProgressView *progressView; @property(nonatomic,weak) DACircularProgressView *circleView;
@end
@implementation ViewController
- (void)viewDidLoad { [super viewDidLoad]; DACircularProgressView *circleView=[[DACircularProgressView alloc]init]; circleView.frame=CGRectMake(100, 100, 100, 100); circleView.trackTintColor=[UIColor blueColor]; circleView.progressTintColor=[UIColor redColor]; circleView.progress=0.0; [self.view addSubview:circleView]; self.circleView=circleView; } -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self download]; } -(void)download { //1-URL NSURL *url=[NSURL URLWithString:@"http://localhost:8080//MJServer/resources/videos.zip"]; //2-请求 NSURLRequest *request=[NSURLRequest requestWithURL:url]; //3-下载 [NSURLConnection connectionWithRequest:request delegate:self]; } #pragma 代理方法
//-请求失败时调用(请求超时,网络异常) -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"didFailWithError--"); } //-接收到服务器的响应聚会调用 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSLog(@"didReceiveResponse--"); self.fileData=[NSMutableData data]; //取出文件的总长度 NSHTTPURLResponse *resp=(NSHTTPURLResponse *)response; //NSLog(@"%@",resp.allHeaderFields); long long fileLength=[resp.allHeaderFields[@"Content-Length"] longLongValue]; //NSLog(@"%lld",fileLength); //NSLog(@"%lld",response.expectedContentLength); self.totalLength=response.expectedContentLength; } //当接收到服务器返回到实体数据时调用(具体内容,这个内容可被调用多次) -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { //static int total=0; //total+=data.length; //NSLog(@"didReceiveData--%d---%d",data.length,total); [self.fileData appendData:data]; //self.progressView.progress=(double)self.fileData.length/self.totalLength; self.circleView.progress=(double)self.fileData.length/self.totalLength; } //加载完毕后调用(服务器的数据已经完全返回后) -(void)connectionDidFinishLoading:(NSURLConnection *)connection { NSLog(@"connectionDidFinishLoading--"); //写入到沙盒中 NSString *cache= [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject]; NSString *file=[cache stringByAppendingPathComponent:@"videos.zip"]; [self.fileData writeToFile:file atomically:YES]; } @end
|