西安做网站公司必达,在哪里建设网站,自己有服务器怎么做网站,建网站所需材料iOS中下载大型文件#xff0c;需要考虑到占用内存的大小与下载速度#xff08;使用多线程#xff09;#xff0c;因此本文首先介绍一个原理性下载文件的DEMO。 在下载大型文件中#xff0c;需要知道下载的进度因此需要使用代理模式#xff0c;不断的回调下载进度。 - (…iOS中下载大型文件需要考虑到占用内存的大小与下载速度使用多线程因此本文首先介绍一个原理性下载文件的DEMO。 在下载大型文件中需要知道下载的进度因此需要使用代理模式不断的回调下载进度。 - (void)downLoad { // 1.URL NSURL *url [NSURL URLWithString:”http://localhost:8080/MJServer/resources/videos.zip“]; // 2.NURLRequest NSURLRequest *request [NSURLRequest requestWithURL:url]; // 3.开始创建TCP连接 [NSURLConnection connectionWithRequest:request delegate:self]; // [[NSURLConnection alloc]initWithRequest:request delegate:self]; // NSURLConnection *connection [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:NO]; // [connection start]; }
下面是代理方法 - (void)connection:(NSURLConnection )connection didFailWithError:(NSError )error { NSLog(”didFailWithError”); } - (void)connection:(NSURLConnection )connection didReceiveResponse:(NSURLResponse )response { self.fileData [NSMutableData data]; // NSHTTPURLResponse * resp (NSHTTPURLResponse*)response; // long long fileLength [resp.allHeaderFields[”Content-Length”]longLongValue]; self.totalLength response.expectedContentLength; } - (void)connection:(NSURLConnection )connection didReceiveData:(NSData )data { [self.fileData appendData:data]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSString *caches [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; NSString *file [caches stringByAppendingPathComponent:”videos.zip”]; [self.fileData writeToFile:file atomically:YES]; }
设计的总思路 1创建NSURLConnection的对象并建立网络下载 2根据代理方法来回调报告下载数据以及进度 3不断的累计下载data (4)最后将下载的数据写入到沙盒缓存中 注意这里的回调方法都是在主线程中执行的.